item_cmpfunc.cc 51.8 KB
Newer Older
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1
/* Copyright (C) 2000-2003
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
12

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

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
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;
}

static void agg_result_type(Item_result *type, Item **items, uint nitems)
{
  uint i;
  type[0]= items[0]->result_type();
  for (i=1 ; i < nitems ; i++)
    type[0]= item_store_type(type[0], items[i]->result_type());
}

static void agg_cmp_type(Item_result *type, Item **items, uint nitems)
{
  uint i;
  type[0]= items[0]->result_type();
  for (i=1 ; i < nitems ; i++)
    type[0]= item_cmp_type(type[0], items[i]->result_type());
}

53 54
static void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname)
{
55
  my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
56 57 58 59 60
  	   c1.collation->name,c1.derivation_name(),
	   c2.collation->name,c2.derivation_name(),
	   fname);
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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);
}
85

bk@work.mysql.com's avatar
bk@work.mysql.com committed
86
/*
87
  Test functions
88 89
  Most of these  returns 0LL if false and 1LL if true and
  NULL if some arg is NULL.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
90 91 92 93 94 95 96 97 98
*/

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

99 100 101 102 103
/*
  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).
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
104 105 106 107

  RESULT VALUES
  0	Can't convert item
  1	Item was replaced with an integer version of the item
108
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
109 110 111

static bool convert_constant_item(Field *field, Item **item)
{
112
  if ((*item)->const_item())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
113
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
114
    if (!(*item)->save_in_field(field, 1) && !((*item)->null_value))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
115
    {
116 117
      Item *tmp=new Item_int_with_ref(field->val_int(), *item);
      if (tmp)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
118
	*item=tmp;
119
      return 1;					// Item was replaced
bk@work.mysql.com's avatar
bk@work.mysql.com committed
120 121 122 123 124
    }
  }
  return 0;
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
125

126 127 128 129 130 131 132 133 134 135
void Item_bool_func2::fix_length_and_dec()
{
  max_length= 1;				     // Function returns 0 or 1

  /*
    As some compare functions are generated after sql_yacc,
    we have to check for out of memory conditions here
  */
  if (!args[0] || !args[1])
    return;
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

  /* 
    We allow to convert to Unicode character sets in some cases.
    The conditions when conversion is possible are:
    - arguments A and B have different charsets
    - A wins according to coercibility rules
    - character set of A is superset for character set of B
   
    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.
  */

  if (args[0] && args[1])
  {
    uint strong= 0;
    uint weak= 0;

154 155 156 157
    if ((args[0]->collation.derivation < args[1]->collation.derivation) && 
	!my_charset_same(args[0]->collation.collation, 
			 args[1]->collation.collation) &&
        (args[0]->collation.collation->state & MY_CS_UNICODE))
158 159 160
    {
      weak= 1;
    }
161 162 163 164
    else if ((args[1]->collation.derivation < args[0]->collation.derivation) && 
	     !my_charset_same(args[0]->collation.collation,
			      args[1]->collation.collation) &&
             (args[1]->collation.collation->state & MY_CS_UNICODE))
165 166 167 168 169 170 171 172 173 174 175 176
    {
      strong= 1;
    }
    
    if (strong || weak)
    {
      Item* conv= 0;
      if (args[weak]->type() == STRING_ITEM)
      {
        String tmp, cstr;
        String *ostr= args[weak]->val_str(&tmp);
        cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), 
177
		  args[strong]->collation.collation);
178
        conv= new Item_string(cstr.ptr(),cstr.length(),cstr.charset(),
179
			      args[weak]->collation.derivation);
180 181 182 183
	((Item_string*)conv)->str_value.copy();
      }
      else
      {
184 185
	conv= new Item_func_conv_charset(args[weak],args[strong]->collation.collation);
        conv->collation.set(args[weak]->collation.derivation);
186 187 188 189
      }
      args[weak]= conv ? conv : args[weak];
    }
  }
190
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
191 192 193 194
  // 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;
195
    if (field->store_for_compare())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
196 197 198
    {
      if (convert_constant_item(field,&args[1]))
      {
199
	cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
200
			 INT_RESULT);		// Works for all types.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
201 202 203 204 205 206 207
	return;
      }
    }
  }
  if (args[1]->type() == FIELD_ITEM)
  {
    Field *field=((Item_field*) args[1])->field;
208
    if (field->store_for_compare())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
209 210 211
    {
      if (convert_constant_item(field,&args[0]))
      {
212 213
	cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
			 INT_RESULT); // Works for all types.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
214 215 216 217
	return;
      }
    }
  }
218
  set_cmp_func();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
219 220
}

221

222
int Arg_comparator::set_compare_func(Item_bool_func2 *item, Item_result type)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
223
{
224
  owner= item;
225 226
  func= comparator_matrix[type][(owner->functype() == Item_func::EQUAL_FUNC)?
				1:0];
227
  if (type == ROW_RESULT)
228
  {
229 230
    uint n= (*a)->cols();
    if (n != (*b)->cols())
231 232 233 234 235
    {
      my_error(ER_CARDINALITY_COL, MYF(0), n);
      comparators= 0;
      return 1;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
236 237 238 239 240
    if (!(comparators= (Arg_comparator *) sql_alloc(sizeof(Arg_comparator)*n)))
      return 1;
    for (uint i=0; i < n; i++)
    {
      if ((*a)->el(i)->cols() != (*b)->el(i)->cols())
241
      {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
242 243
	my_error(ER_CARDINALITY_COL, MYF(0), (*a)->el(i)->cols());
	return 1;
244
      }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
245 246
      comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i));
    }
247
  }
248 249 250 251 252 253
  else if (type == STRING_RESULT)
  {
    /*
      We must set cmp_charset here as we may be called from for an automatic
      generated item, like in natural join
    */
254 255
    if (cmp_collation.set((*a)->collation, (*b)->collation) || 
	cmp_collation.derivation == DERIVATION_NONE)
256 257 258 259 260
    {
      my_coll_agg_error((*a)->collation, (*b)->collation, owner->func_name());
      return 1;
    }
  }
261
  return 0;
262
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
263

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
264

265
int Arg_comparator::compare_string()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
266 267
{
  String *res1,*res2;
268
  if ((res1= (*a)->val_str(&owner->tmp_value1)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
269
  {
270
    if ((res2= (*b)->val_str(&owner->tmp_value2)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
271
    {
272
      owner->null_value= 0;
273
      return sortcmp(res1,res2,cmp_collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
274 275
    }
  }
276
  owner->null_value= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
277 278 279
  return -1;
}

280 281 282
int Arg_comparator::compare_e_string()
{
  String *res1,*res2;
283 284
  res1= (*a)->val_str(&owner->tmp_value1);
  res2= (*b)->val_str(&owner->tmp_value2);
285 286
  if (!res1 || !res2)
    return test(res1 == res2);
287
  return test(sortcmp(res1, res2, cmp_collation.collation) == 0);
288 289 290
}


291
int Arg_comparator::compare_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
292
{
293 294
  double val1= (*a)->val();
  if (!(*a)->null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
295
  {
296 297
    double val2= (*b)->val();
    if (!(*b)->null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
298
    {
299
      owner->null_value= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
300 301 302 303 304
      if (val1 < val2)	return -1;
      if (val1 == val2) return 0;
      return 1;
    }
  }
305
  owner->null_value= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
306 307 308
  return -1;
}

309 310
int Arg_comparator::compare_e_real()
{
311 312 313 314
  double val1= (*a)->val();
  double val2= (*b)->val();
  if ((*a)->null_value || (*b)->null_value)
    return test((*a)->null_value && (*b)->null_value);
315 316
  return test(val1 == val2);
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
317

318
int Arg_comparator::compare_int()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
319
{
320 321
  longlong val1= (*a)->val_int();
  if (!(*a)->null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
322
  {
323 324
    longlong val2= (*b)->val_int();
    if (!(*b)->null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
325
    {
326
      owner->null_value= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
327 328 329 330 331
      if (val1 < val2)	return -1;
      if (val1 == val2)   return 0;
      return 1;
    }
  }
332
  owner->null_value= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
333 334 335
  return -1;
}

336 337
int Arg_comparator::compare_e_int()
{
338 339 340 341
  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);
342 343 344 345
  return test(val1 == val2);
}


346
int Arg_comparator::compare_row()
347 348
{
  int res= 0;
349 350
  (*a)->bring_value();
  (*b)->bring_value();
351
  uint n= (*a)->cols();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
352
  for (uint i= 0; i<n; i++)
353
  {
354
    if ((res= comparators[i].compare()))
355 356 357 358 359 360
      return res;
    if (owner->null_value)
      return -1;
  }
  return res;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
361

362 363 364
int Arg_comparator::compare_e_row()
{
  int res= 0;
365 366
  (*a)->bring_value();
  (*b)->bring_value();
367
  uint n= (*a)->cols();
368 369
  for (uint i= 0; i<n; i++)
  {
370 371
    if ((res= !comparators[i].compare()))
      return 0;
372 373 374 375
  }
  return 1;
}

376 377 378 379

bool Item_in_optimizer::fix_left(THD *thd,
				 struct st_table_list *tables,
				 Item **ref)
380
{
381 382 383 384
  if (args[0]->fix_fields(thd, tables, ref) ||
      (!cache && !(cache= Item_cache::get_cache(args[0]->result_type()))))
    return 1;
  cache->setup(args[0]);
385
  cache->store(args[0]);
386
  if (cache->cols() == 1)
387
  {
388
    if ((used_tables_cache= args[0]->used_tables()))
389
      cache->set_used_tables(OUTER_REF_TABLE_BIT);
390 391 392
    else
      cache->set_used_tables(0);
  }
393 394 395 396
  else
  {
    uint n= cache->cols();
    for (uint i= 0; i < n; i++)
397 398
    {
      if (args[0]->el(i)->used_tables())
399
	((Item_cache *)cache->el(i))->set_used_tables(OUTER_REF_TABLE_BIT);
400 401 402
      else
	((Item_cache *)cache->el(i))->set_used_tables(0);
    }
403
    used_tables_cache= args[0]->used_tables();
404
  }
405 406 407
  not_null_tables_cache= args[0]->not_null_tables();
  with_sum_func= args[0]->with_sum_func;
  const_item_cache= args[0]->const_item();
408 409 410 411 412 413 414 415 416 417 418 419 420
  return 0;
}



bool Item_in_optimizer::fix_fields(THD *thd, struct st_table_list *tables,
				   Item ** ref)
{
  if (fix_left(thd, tables, ref))
    return 1;
  if (args[0]->maybe_null)
    maybe_null=1;

421
  if (!args[1]->fixed && args[1]->fix_fields(thd, tables, args))
422 423 424 425 426
    return 1;
  Item_in_subselect * sub= (Item_in_subselect *)args[1];
  if (args[0]->cols() != sub->engine->cols())
  {
    my_error(ER_CARDINALITY_COL, MYF(0), args[0]->cols());
427
    return 1;
428
  }
429 430 431 432
  if (args[1]->maybe_null)
    maybe_null=1;
  with_sum_func= with_sum_func || args[1]->with_sum_func;
  used_tables_cache|= args[1]->used_tables();
433
  not_null_tables_cache|= args[1]->not_null_tables();
434 435 436 437
  const_item_cache&= args[1]->const_item();
  return 0;
}

438 439
longlong Item_in_optimizer::val_int()
{
440 441
  cache->store(args[0]);
  if (cache->null_value)
442 443 444 445 446
  {
    null_value= 1;
    return 0;
  }
  longlong tmp= args[1]->val_int_result();
447
  null_value= args[1]->null_value;
448 449 450
  return tmp;
}

451
bool Item_in_optimizer::is_null()
452
{
453 454
  cache->store(args[0]);
  return (null_value= (cache->null_value || args[1]->is_null()));
455
}
456

bk@work.mysql.com's avatar
bk@work.mysql.com committed
457 458
longlong Item_func_eq::val_int()
{
459
  int value= cmp.compare();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
460 461 462 463 464
  return value == 0 ? 1 : 0;
}

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

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
465 466 467 468 469 470
void Item_func_equal::fix_length_and_dec()
{
  Item_bool_func2::fix_length_and_dec();
  maybe_null=null_value=0;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
471 472
longlong Item_func_equal::val_int()
{
473
  return cmp.compare();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
474 475 476 477
}

longlong Item_func_ne::val_int()
{
478
  int value= cmp.compare();
479
  return value != 0 && !null_value ? 1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
480 481 482 483 484
}


longlong Item_func_ge::val_int()
{
485
  int value= cmp.compare();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
486 487 488 489 490 491
  return value >= 0 ? 1 : 0;
}


longlong Item_func_gt::val_int()
{
492
  int value= cmp.compare();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
493 494 495 496 497
  return value > 0 ? 1 : 0;
}

longlong Item_func_le::val_int()
{
498
  int value= cmp.compare();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
499 500 501 502 503 504
  return value <= 0 && !null_value ? 1 : 0;
}


longlong Item_func_lt::val_int()
{
505
  int value= cmp.compare();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
506 507 508 509 510 511 512 513 514 515 516 517 518
  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;
  }
519
  int value= sortcmp(a,b,cmp.cmp_collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
520 521 522 523 524 525 526
  null_value=0;
  return !value ? 0 : (value < 0 ? (longlong) -1 : (longlong) 1);
}


void Item_func_interval::fix_length_and_dec()
{
527
  if (row->cols() > 8)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
528
  {
529 530 531
    bool consts=1;

    for (uint i=1 ; consts && i < row->cols() ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
532
    {
533
      consts&= row->el(i)->const_item();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
534
    }
535 536 537

    if (consts &&
        (intervals=(double*) sql_alloc(sizeof(double)*(row->cols()-1))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
538
    {
539 540
      for (uint i=1 ; i < row->cols(); i++)
        intervals[i-1]=row->el(i)->val();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
541 542
    }
  }
543 544
  maybe_null= 0;
  max_length= 2;
545
  used_tables_cache|= row->used_tables();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
546
  not_null_tables_cache&= row->not_null_tables();
547
  with_sum_func= with_sum_func || row->with_sum_func;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
548 549
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
550

bk@work.mysql.com's avatar
bk@work.mysql.com committed
551 552 553
/*
  return -1 if null value,
	  0 if lower than lowest
554 555
	  1 - arg_count-1 if between args[n] and args[n+1]
	  arg_count if higher than biggest argument
bk@work.mysql.com's avatar
bk@work.mysql.com committed
556 557 558 559
*/

longlong Item_func_interval::val_int()
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
560 561 562
  double value= row->el(0)->val();
  uint i;

563 564
  if (row->el(0)->null_value)
    return -1;				// -1 if null
bk@work.mysql.com's avatar
bk@work.mysql.com committed
565 566 567
  if (intervals)
  {					// Use binary search to find interval
    uint start,end;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
568 569
    start= 1;
    end=   row->cols()-2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
570 571
    while (start != end)
    {
ram@mysql.r18.ru's avatar
ram@mysql.r18.ru committed
572
      uint mid= (start + end + 1) / 2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
573
      if (intervals[mid] <= value)
ram@mysql.r18.ru's avatar
ram@mysql.r18.ru committed
574
	start= mid;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
575
      else
ram@mysql.r18.ru's avatar
ram@mysql.r18.ru committed
576
	end= mid - 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
577
    }
ram@mysql.r18.ru's avatar
ram@mysql.r18.ru committed
578
    return (value < intervals[start]) ? 0 : start + 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
579
  }
580 581

  for (i=1 ; i < row->cols() ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
582
  {
583 584
    if (row->el(i)->val() > value)
      return i-1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
585
  }
586
  return i-1;
587 588
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
589 590
void Item_func_between::fix_length_and_dec()
{
591
   max_length= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
592

593 594 595 596
  /*
    As some compare functions are generated after sql_yacc,
    we have to check for out of memory conditons here
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
597 598
  if (!args[0] || !args[1] || !args[2])
    return;
599
  agg_cmp_type(&cmp_type, args, 3);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
600 601 602
  if (cmp_type == STRING_RESULT &&
      agg_arg_collations_for_comparison(cmp_collation, args, 3))
    return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
603

serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
604 605 606 607 608
  /*
    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
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
  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)
634 635
      return (sortcmp(value,a,cmp_collation.collation) >= 0 && 
	      sortcmp(value,b,cmp_collation.collation) <= 0) ? 1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
636 637 638 639
    if (args[1]->null_value && args[2]->null_value)
      null_value=1;
    else if (args[1]->null_value)
    {
640
      null_value= sortcmp(value,b,cmp_collation.collation) <= 0; // not null if false range.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
641 642 643
    }
    else
    {
644
      null_value= sortcmp(value,a,cmp_collation.collation) >= 0; // not null if false range.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
645 646 647 648 649 650
    }
  }
  else if (cmp_type == INT_RESULT)
  {
    longlong value=args[0]->val_int(),a,b;
    if ((null_value=args[0]->null_value))
651
      return 0;					/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    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))
671
      return 0;					/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    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;
}

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);
696
  agg_result_type(&cached_result_type, args, 2);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
697 698
  if (cached_result_type == STRING_RESULT)
    agg_arg_collations(collation, args, arg_count);
699 700
  else if (cached_result_type != REAL_RESULT)
    decimals= 0;
701 702 703 704 705 706 707 708 709
  
  cached_field_type= args[0]->field_type();
  if (cached_field_type != args[1]->field_type())
    cached_field_type= Item_func::field_type();
}

enum_field_types Item_func_ifnull::field_type() const 
{
  return cached_field_type;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
710 711
}

712 713 714 715
Field *Item_func_ifnull::tmp_table_field(TABLE *table)
{
  return tmp_table_field_from_field_type(table);
}
716

bk@work.mysql.com's avatar
bk@work.mysql.com committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
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;
754
    res->set_charset(collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
755 756 757 758 759
    return res;
  }
  res=args[1]->val_str(str);
  if ((null_value=args[1]->null_value))
    return 0;
760
  res->set_charset(collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
761 762 763
  return res;
}

764

bk@work.mysql.com's avatar
bk@work.mysql.com committed
765 766 767 768 769
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);
770
  decimals=max(args[1]->decimals,args[2]->decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
771 772
  enum Item_result arg1_type=args[1]->result_type();
  enum Item_result arg2_type=args[2]->result_type();
773 774 775 776 777 778
  bool null1=args[1]->null_value;
  bool null2=args[2]->null_value;

  if (null1)
  {
    cached_result_type= arg2_type;
779
    collation.set(args[2]->collation.collation);
780 781 782
  }
  else if (null2)
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
783
    cached_result_type= arg1_type;
784
    collation.set(args[1]->collation.collation);
785
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
786
  else
787
  {
788 789 790 791 792 793
    agg_result_type(&cached_result_type, args+1, 2);
    if (cached_result_type == STRING_RESULT)
    {
      if (agg_arg_collations(collation, args+1, 2))
      return;
    }
794
    else
795
    {
796
      collation.set(&my_charset_bin);	// Number
797
    }
798
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
}


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);
825
  if (res)
826
    res->set_charset(collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
827 828 829 830 831 832 833 834 835 836 837 838 839 840
  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;
841
    agg_result_type(&cached_result_type, args, 2);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
842 843 844 845
  }
}

/*
846
  nullif () returns NULL if arguments are different, else it returns the
bk@work.mysql.com's avatar
bk@work.mysql.com committed
847 848 849 850 851 852 853 854 855
  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;
856
  if (!cmp.compare() || null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
857 858 859 860 861 862 863 864 865 866 867 868 869
  {
    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;
870
  if (!cmp.compare() || null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
871 872 873 874 875 876 877 878 879 880 881 882 883
  {
    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;
884
  if (!cmp.compare() || null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
885 886 887 888 889 890 891 892 893 894
  {
    null_value=1;
    return 0;
  }
  res=args[0]->val_str(str);
  null_value=args[0]->null_value;
  return res;
}

/*
895 896
  CASE expression 
  Return the matching ITEM or NULL if all compares (including else) failed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
897 898 899 900 901 902 903
*/

Item *Item_func_case::find_item(String *str)
{
  String *first_expr_str,*tmp;
  longlong first_expr_int;
  double   first_expr_real;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
904
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
905 906 907 908 909
  /* These will be initialized later */
  LINT_INIT(first_expr_str);
  LINT_INIT(first_expr_int);
  LINT_INIT(first_expr_real);

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
  if (first_expr_num != -1)
  {
    switch (cmp_type)
    {
      case STRING_RESULT:
      	// We can't use 'str' here as this may be overwritten
	if (!(first_expr_str= args[first_expr_num]->val_str(&str_value)))
	  return else_expr_num != -1 ? args[else_expr_num] : 0;	// Impossible
        break;
      case INT_RESULT:
	first_expr_int= args[first_expr_num]->val_int();
	if (args[first_expr_num]->null_value)
	  return else_expr_num != -1 ? args[else_expr_num] : 0;
	break;
      case REAL_RESULT:
	first_expr_real= args[first_expr_num]->val();
	if (args[first_expr_num]->null_value)
	  return else_expr_num != -1 ? args[else_expr_num] : 0;
	break;
      case ROW_RESULT:
      default:
	// This case should never be choosen
	DBUG_ASSERT(0);
	break;
    }
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
937
  // Compare every WHEN argument with it and return the first match
938
  for (uint i=0 ; i < ncases ; i+=2)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
939
  {
940
    if (first_expr_num == -1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
941
    {
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
942
      // No expression between CASE and the first WHEN
bk@work.mysql.com's avatar
bk@work.mysql.com committed
943 944 945 946
      if (args[i]->val_int())
	return args[i+1];
      continue;
    }
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
947
    switch (cmp_type) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
948 949
    case STRING_RESULT:
      if ((tmp=args[i]->val_str(str)))		// If not null
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
950
	if (sortcmp(tmp,first_expr_str,cmp_collation.collation)==0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
951 952 953 954 955 956 957 958 959
	  return args[i+1];
      break;
    case INT_RESULT:
      if (args[i]->val_int()==first_expr_int && !args[i]->null_value) 
        return args[i+1];
      break;
    case REAL_RESULT: 
      if (args[i]->val()==first_expr_real && !args[i]->null_value) 
        return args[i+1];
960
      break;
961
    case ROW_RESULT:
962
    default:
963 964 965
      // This case should never be choosen
      DBUG_ASSERT(0);
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
966 967 968
    }
  }
  // No, WHEN clauses all missed, return ELSE expression
969
  return else_expr_num != -1 ? args[else_expr_num] : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
970 971 972 973 974 975 976 977 978 979 980 981 982 983
}



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

  if (!item)
  {
    null_value=1;
    return 0;
  }
984
  null_value= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
985
  if (!(res=item->val_str(str)))
986
    null_value= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
987 988 989 990 991 992 993
  return res;
}


longlong Item_func_case::val_int()
{
  char buff[MAX_FIELD_WIDTH];
994
  String dummy_str(buff,sizeof(buff),default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
  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];
1011
  String dummy_str(buff,sizeof(buff),default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  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;
}

void Item_func_case::fix_length_and_dec()
1026
{
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
  Item **agg;
  uint nagg;
  
  if (!(agg= (Item**) sql_alloc(sizeof(Item*)*(ncases+1))))
    return;
  
  // Aggregate all THEN and ELSE expression types
  // and collations when string result
  
  for (nagg= 0 ; nagg < ncases/2 ; nagg++)
    agg[nagg]= args[nagg*2+1];
  
  if (else_expr_num != -1)
    agg[nagg++]= args[else_expr_num];
  
  agg_result_type(&cached_result_type, agg, nagg);
  if ((cached_result_type == STRING_RESULT) &&
      agg_arg_collations(collation, agg, nagg))
    return;
  
  
  //  Aggregate first expression and all THEN expression types
  //  and collations when string comparison
1050
  if (first_expr_num != -1)
1051
  {
1052 1053
    agg[0]= args[first_expr_num];
    for (nagg= 0; nagg < ncases/2 ; nagg++)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1054
      agg[nagg+1]= args[nagg*2];
1055 1056 1057 1058 1059
    nagg++;
    agg_cmp_type(&cmp_type, agg, nagg);
    if ((cmp_type == STRING_RESULT) &&
        agg_arg_collations_for_comparison(cmp_collation, agg, nagg))
    return;
1060
  }
1061
  
1062 1063
  if (!else_expr_num != -1 || args[else_expr_num]->maybe_null)
    maybe_null=1;
1064
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1065 1066
  max_length=0;
  decimals=0;
1067
  for (uint i=0 ; i < ncases ; i+=2)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1068 1069 1070 1071
  {
    set_if_bigger(max_length,args[i+1]->max_length);
    set_if_bigger(decimals,args[i+1]->decimals);
  }
1072
  if (else_expr_num != -1) 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1073
  {
1074 1075
    set_if_bigger(max_length,args[else_expr_num]->max_length);
    set_if_bigger(decimals,args[else_expr_num]->decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1076 1077 1078
  }
}

1079
/* TODO:  Fix this so that it prints the whole CASE expression */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1080 1081 1082 1083 1084 1085 1086

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

/*
1087
  Coalesce - return first not NULL argument.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1088 1089 1090 1091 1092 1093 1094
*/

String *Item_func_coalesce::val_str(String *str)
{
  null_value=0;
  for (uint i=0 ; i < arg_count ; i++)
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1095 1096 1097
    String *res;
    if ((res=args[i]->val_str(str)))
      return res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
  }
  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()
{
1132 1133
  max_length= 0;
  decimals= 0;
1134
  agg_result_type(&cached_result_type, args, arg_count);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1135 1136 1137 1138 1139
  for (uint i=0 ; i < arg_count ; i++)
  {
    set_if_bigger(max_length,args[i]->max_length);
    set_if_bigger(decimals,args[i]->decimals);
  }
1140 1141 1142 1143
  if (cached_result_type == STRING_RESULT)
    agg_arg_collations(collation, args, arg_count);
  else if (cached_result_type != REAL_RESULT)
    decimals= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1144 1145 1146
}

/****************************************************************************
1147
 Classes and function for the IN operator
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1148 1149
****************************************************************************/

1150
static int cmp_longlong(void *cmp_arg, longlong *a,longlong *b)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1151 1152 1153 1154
{
  return *a < *b ? -1 : *a == *b ? 0 : 1;
}

1155
static int cmp_double(void *cmp_arg, double *a,double *b)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1156 1157 1158 1159
{
  return *a < *b ? -1 : *a == *b ? 0 : 1;
}

1160
static int cmp_row(void *cmp_arg, cmp_item_row* a, cmp_item_row* b)
1161 1162 1163 1164
{
  return a->compare(b);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
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;
1177
    if ((res=(*compare)(collation, base+mid*size, result)) == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1178 1179 1180 1181 1182 1183
      return 1;
    if (res < 0)
      start=mid;
    else
      end=mid-1;
  }
1184
  return (int) ((*compare)(collation, base+start*size, result) == 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1185 1186
}

1187 1188
in_string::in_string(uint elements,qsort2_cmp cmp_func, CHARSET_INFO *cs)
  :in_vector(elements, sizeof(String), cmp_func, cs),
1189
   tmp(buff, sizeof(buff), &my_charset_bin)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1190 1191 1192 1193
{}

in_string::~in_string()
{
1194
  if (base)
1195
  {
1196
    // base was allocated with help of sql_alloc => following is OK
1197 1198
    for (uint i=0 ; i < count ; i++)
      ((String*) base)[i].free();
1199
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1200 1201 1202 1203 1204 1205 1206 1207
}

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;
1208
  if (!str->charset())
1209 1210
  {
    CHARSET_INFO *cs;
1211
    if (!(cs= item->collation.collation))
1212
      cs= &my_charset_bin;		// Should never happen for STR items
1213 1214
    str->set_charset(cs);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1215 1216
}

1217

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1218 1219 1220 1221 1222
byte *in_string::get_value(Item *item)
{
  return (byte*) item->val_str(&tmp);
}

1223 1224
in_row::in_row(uint elements, Item * item)
{
1225
  base= (char*) new cmp_item_row[count= elements];
1226
  size= sizeof(cmp_item_row);
1227
  compare= (qsort2_cmp) cmp_row;
1228
  tmp.store_value(item);
1229 1230 1231 1232 1233
}

in_row::~in_row()
{
  if (base)
1234
    delete [] (cmp_item_row*) base;
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
}

byte *in_row::get_value(Item *item)
{
  tmp.store_value(item);
  return (byte *)&tmp;
}

void in_row::set(uint pos, Item *item)
{
  DBUG_ENTER("in_row::set");
  DBUG_PRINT("enter", ("pos %u item 0x%lx", pos, (ulong) item));
  ((cmp_item_row*) base)[pos].store_value_by_template(&tmp, item);
  DBUG_VOID_RETURN;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1250 1251

in_longlong::in_longlong(uint elements)
1252
  :in_vector(elements,sizeof(longlong),(qsort2_cmp) cmp_longlong, 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1253 1254 1255 1256 1257 1258 1259 1260 1261
{}

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

byte *in_longlong::get_value(Item *item)
{
1262
  tmp= item->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1263
  if (item->null_value)
1264
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1265 1266 1267 1268
  return (byte*) &tmp;
}

in_double::in_double(uint elements)
1269
  :in_vector(elements,sizeof(double),(qsort2_cmp) cmp_double, 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1270 1271 1272 1273 1274 1275 1276 1277 1278
{}

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

byte *in_double::get_value(Item *item)
{
1279
  tmp= item->val();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1280
  if (item->null_value)
1281
    return 0;					/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1282 1283 1284
  return (byte*) &tmp;
}

1285
cmp_item* cmp_item::get_comparator(Item *item)
1286 1287 1288
{
  switch (item->result_type()) {
  case STRING_RESULT:
1289
    return new cmp_item_sort_string(item->collation.collation);
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    break;
  case INT_RESULT:
    return new cmp_item_int;
    break;
  case REAL_RESULT:
    return new cmp_item_real;
    break;
  case ROW_RESULT:
    return new cmp_item_row;
    break;
1300 1301 1302
  default:
    DBUG_ASSERT(0);
    break;
1303 1304 1305 1306
  }
  return 0; // to satisfy compiler :)
}

1307 1308
cmp_item* cmp_item_sort_string::make_same()
{
1309
  return new cmp_item_sort_string_in_static(cmp_charset);
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
}

cmp_item* cmp_item_int::make_same()
{
  return new cmp_item_int();
}

cmp_item* cmp_item_real::make_same()
{
  return new cmp_item_real();
}

cmp_item* cmp_item_row::make_same()
{
  return new cmp_item_row();
}

1327 1328
void cmp_item_row::store_value(Item *item)
{
1329
  THD *thd= current_thd;
1330
  n= item->cols();
1331
  if ((comparators= (cmp_item **) thd->calloc(sizeof(cmp_item *)*n)))
1332
  {
1333
    item->bring_value();
1334
    item->null_value= 0;
1335 1336
    for (uint i=0; i < n; i++)
      if ((comparators[i]= cmp_item::get_comparator(item->el(i))))
1337
      {
1338
	comparators[i]->store_value(item->el(i));
1339 1340
	item->null_value|= item->el(i)->null_value;
      }
1341 1342 1343 1344 1345 1346 1347
      else
	return;
  }
  else
    return;
}

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
void cmp_item_row::store_value_by_template(cmp_item *t, Item *item)
{
  cmp_item_row *tmpl= (cmp_item_row*) t;
  if (tmpl->n != item->cols())
  {
    my_error(ER_CARDINALITY_COL, MYF(0), tmpl->n);
    return;
  }
  n= tmpl->n;
  if ((comparators= (cmp_item **) sql_alloc(sizeof(cmp_item *)*n)))
  {
1359
    item->bring_value();
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
    item->null_value= 0;
    for (uint i=0; i < n; i++)
      if ((comparators[i]= tmpl->comparators[i]->make_same()))
      {
	comparators[i]->store_value_by_template(tmpl->comparators[i],
						item->el(i));
	item->null_value|= item->el(i)->null_value;
      }
      else
	return;
  }
  else
    return;
}

1375 1376
int cmp_item_row::cmp(Item *arg)
{
1377 1378 1379 1380 1381 1382
  arg->null_value= 0;
  if (arg->cols() != n)
  {
    my_error(ER_CARDINALITY_COL, MYF(0), n);
    return 1;
  }
1383
  bool was_null= 0;
1384
  arg->bring_value();
1385 1386
  for (uint i=0; i < n; i++)
    if (comparators[i]->cmp(arg->el(i)))
1387
    {
1388 1389 1390
      if (!arg->el(i)->null_value)
	return 1;
      was_null= 1;
1391
    }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1392
  return (arg->null_value= was_null);
1393 1394 1395 1396 1397 1398
}

int cmp_item_row::compare(cmp_item *c)
{
  int res;
  cmp_item_row *cmp= (cmp_item_row *) c;
1399 1400
  for (uint i=0; i < n; i++)
    if ((res= comparators[i]->compare(cmp->comparators[i])))
1401
      return res;
1402 1403
  return 0;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1404

1405 1406 1407
bool Item_func_in::nulls_in_row()
{
  Item **arg,**arg_end;
1408
  for (arg= args+1, arg_end= args+arg_count; arg != arg_end ; arg++)
1409 1410 1411 1412 1413 1414 1415
  {
    if ((*arg)->null_inside())
      return 1;
  }
  return 0;
}

1416
static int srtcmp_in(CHARSET_INFO *cs, const String *x,const String *y)
1417
{
1418
  return cs->coll->strnncollsp(cs,
1419 1420 1421 1422
                        (unsigned char *) x->ptr(),x->length(),
			(unsigned char *) y->ptr(),y->length());
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1423 1424
void Item_func_in::fix_length_and_dec()
{
1425 1426 1427
  Item **arg, **arg_end;
  uint const_itm= 1;
  
1428 1429
  agg_cmp_type(&cmp_type, args, arg_count);
  if ((cmp_type == STRING_RESULT) &&
1430 1431 1432 1433 1434 1435
      (agg_arg_collations_for_comparison(cmp_collation, args, arg_count)))
    return;
  
  for (arg=args+1, arg_end=args+arg_count; arg != arg_end ; arg++)
    const_itm&= arg[0]->const_item();
  
1436 1437 1438 1439
  /*
    Row item with NULLs inside can return NULL or FALSE => 
    they can't be processed as static
  */
1440
  if (const_itm && !nulls_in_row())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1441
  {
1442
    switch (cmp_type) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1443
    case STRING_RESULT:
1444
      uint i;
1445
      array=new in_string(arg_count-1,(qsort2_cmp) srtcmp_in, 
1446
			  cmp_collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1447 1448
      break;
    case INT_RESULT:
1449
      array= new in_longlong(arg_count-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1450 1451
      break;
    case REAL_RESULT:
1452
      array= new in_double(arg_count-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1453
      break;
1454
    case ROW_RESULT:
1455
      array= new in_row(arg_count-1, args[0]);
1456
      break;
1457 1458 1459
    default:
      DBUG_ASSERT(0);
      return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1460 1461
    }
    uint j=0;
1462
    for (uint i=1 ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1463 1464
    {
      array->set(j,args[i]);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1465
      if (!args[i]->null_value)			// Skip NULL values
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1466
	j++;
1467 1468
      else
	have_null= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1469 1470 1471 1472 1473 1474
    }
    if ((array->used_count=j))
      array->sort();
  }
  else
  {
1475
    in_item= cmp_item::get_comparator(args[0]);
1476
    if (cmp_type  == STRING_RESULT)
1477
      in_item->cmp_charset= cmp_collation.collation;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1478
  }
1479
  maybe_null= args[0]->maybe_null;
1480
  max_length= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
}


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


longlong Item_func_in::val_int()
{
  if (array)
  {
1496 1497
    int tmp=array->find(args[0]);
    null_value=args[0]->null_value || (!tmp && have_null);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1498 1499
    return tmp;
  }
1500 1501
  in_item->store_value(args[0]);
  if ((null_value=args[0]->null_value))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1502
    return 0;
1503
  have_null= 0;
1504
  for (uint i=1 ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1505 1506 1507
  {
    if (!in_item->cmp(args[i]) && !args[i]->null_value)
      return 1;					// Would maybe be nice with i ?
1508
    have_null|= args[i]->null_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1509
  }
1510
  null_value= have_null;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
  return 0;
}


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

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
Item_cond::Item_cond(THD *thd, Item_cond &item)
  :Item_bool_func(thd, item),
   abort_on_null(item.abort_on_null),
   and_tables_cache(item.and_tables_cache)
{
  /*
    here should be following text:

  List_iterator_fast<Item*> li(item.list);
  while(Item *it= li++)
    list.push_back(it);

    but it do not need,
    because this constructor used only for AND/OR and
    argument list will be copied by copy_andor_arguments call
  */

}

void Item_cond::copy_andor_arguments(THD *thd, Item_cond *item)
{
  List_iterator_fast<Item> li(item->list);
  while(Item *it= li++)
    list.push_back(it->copy_andor_structure(thd));
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1577 1578

bool
1579
Item_cond::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1580 1581 1582
{
  List_iterator<Item> li(list);
  Item *item;
1583
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1584
  char buff[sizeof(char*)];			// Max local vars in function
1585
#endif
1586 1587
  not_null_tables_cache= used_tables_cache= 0;
  const_item_cache= 0;
1588 1589 1590 1591 1592
  /*
    and_table_cache is the value that Item_cond_or() returns for
    not_null_tables()
  */
  and_tables_cache= ~(table_map) 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1593 1594 1595 1596 1597

  if (thd && check_stack_overrun(thd,buff))
    return 0;					// Fatal error flag is set!
  while ((item=li++))
  {
1598
    table_map tmp_table_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
    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
    }
1609 1610
    if (abort_on_null)
      item->top_level_item();
1611 1612
    if ((!item->fixed &&
	 item->fix_fields(thd, tables, li.ref())) || item->check_cols(1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1613
      return 1; /* purecov: inspected */
1614 1615 1616 1617 1618 1619
    used_tables_cache|=     item->used_tables();
    tmp_table_map=	    item->not_null_tables();
    not_null_tables_cache|= tmp_table_map;
    and_tables_cache&=      tmp_table_map;
    const_item_cache&=	    item->const_item();
    with_sum_func=	    with_sum_func || item->with_sum_func;
1620 1621
    if (item->maybe_null)
      maybe_null=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1622 1623
  }
  if (thd)
1624
    thd->lex.current_select->cond_count+=list.elements;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1625
  fix_length_and_dec();
1626
  fixed= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1627 1628 1629
  return 0;
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
bool Item_cond::walk(Item_processor processor, byte *arg)
{
  List_iterator_fast<Item> li(list);
  Item *item;
  while ((item= li++))
    if (item->walk(processor, arg))
      return 1;
  return Item_func::walk(processor, arg);
}

1640
void Item_cond::split_sum_func(Item **ref_pointer_array, List<Item> &fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1641 1642 1643 1644 1645 1646 1647 1648
{
  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)
1649
      item->split_sum_func(ref_pointer_array, fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1650 1651
    else if (item->used_tables() || item->type() == SUM_FUNC_ITEM)
    {
1652
      uint el= fields.elements;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1653
      fields.push_front(item);
1654 1655
      ref_pointer_array[el]= item;
      li.replace(new Item_ref(ref_pointer_array + el, 0, item->name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
    }
    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;
}

1670

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1671 1672
void Item_cond::update_used_tables()
{
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1673
  List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1674
  Item *item;
1675 1676 1677

  used_tables_cache=0;
  const_item_cache=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1678 1679 1680
  while ((item=li++))
  {
    item->update_used_tables();
1681 1682
    used_tables_cache|= item->used_tables();
    const_item_cache&=  item->const_item();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1683 1684 1685 1686 1687 1688 1689
  }
}


void Item_cond::print(String *str)
{
  str->append('(');
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1690
  List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
  Item *item;
  if ((item=li++))
    item->print(str);
  while ((item=li++))
  {
    str->append(' ');
    str->append(func_name());
    str->append(' ');
    item->print(str);
  }
  str->append(')');
}

1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
/*
  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
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1721 1722 1723

longlong Item_cond_and::val_int()
{
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1724
  List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1725
  Item *item;
1726
  null_value= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1727 1728 1729 1730
  while ((item=li++))
  {
    if (item->val_int() == 0)
    {
1731 1732
      if (abort_on_null || !(null_value= item->null_value))
	return 0;				// return FALSE
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1733 1734
    }
  }
1735
  return null_value ? 0 : 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1736 1737
}

1738

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1739 1740
longlong Item_cond_or::val_int()
{
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1741
  List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
  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;
}

1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
/*
  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)
1781
    return (*org_item= (Item*) b);
1782 1783 1784
  if (a == *org_item)
  {
    Item_cond *res;
1785
    if ((res= new Item_cond_and(a, (Item*) b)))
1786
    {
1787
      res->used_tables_cache= a->used_tables() | b->used_tables();
1788 1789
      res->not_null_tables_cache= a->not_null_tables() | b->not_null_tables();
    }
1790 1791
    return res;
  }
1792
  if (((Item_cond_and*) a)->add((Item*) b))
1793 1794
    return 0;
  ((Item_cond_and*) a)->used_tables_cache|= b->used_tables();
1795
  ((Item_cond_and*) a)->not_null_tables_cache|= b->not_null_tables();
1796 1797 1798 1799
  return a;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1800 1801
longlong Item_func_isnull::val_int()
{
1802 1803 1804 1805 1806
  /*
    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)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1807
    return cached_value;
1808
  return args[0]->is_null() ? 1: 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1809 1810
}

1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
longlong Item_is_not_null_test::val_int()
{
  DBUG_ENTER("Item_is_not_null_test::val_int");
  if (!used_tables_cache)
  {
    owner->was_null|= (!cached_value);
    DBUG_PRINT("info", ("cached :%d", cached_value));
    DBUG_RETURN(cached_value);
  }
  if (args[0]->is_null())
  {
    DBUG_PRINT("info", ("null"))
    owner->was_null|= 1;
    DBUG_RETURN(0);
  }
  else
    DBUG_RETURN(1);
}

/* Optimize case of not_null_column IS NULL */
void Item_is_not_null_test::update_used_tables()
{
  if (!args[0]->maybe_null)
  {
    used_tables_cache= 0;			/* is always true */
    cached_value= (longlong) 1;
  }
  else
  {
    args[0]->update_used_tables();
    if (!(used_tables_cache=args[0]->used_tables()))
    {
      /* Remember if the value is always NULL or never NULL */
      cached_value= (longlong) !args[0]->is_null();
    }
  }
}
1848

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1849 1850
longlong Item_func_isnotnull::val_int()
{
1851
  return args[0]->is_null() ? 0 : 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1852 1853 1854 1855 1856
}


longlong Item_func_like::val_int()
{
1857
  String* res = args[0]->val_str(&tmp_value1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1858 1859 1860 1861 1862
  if (args[0]->null_value)
  {
    null_value=1;
    return 0;
  }
1863
  String* res2 = args[1]->val_str(&tmp_value2);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1864 1865 1866 1867 1868 1869
  if (args[1]->null_value)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
1870 1871
  if (canDoTurboBM)
    return turboBM_matches(res->ptr(), res->length()) ? 1 : 0;
1872
  return my_wildcmp(cmp.cmp_collation.collation,
1873 1874 1875
		    res->ptr(),res->ptr()+res->length(),
		    res2->ptr(),res2->ptr()+res2->length(),
		    escape,wild_one,wild_many) ? 0 : 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1876 1877 1878 1879 1880 1881 1882
}


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

Item_func::optimize_type Item_func_like::select_optimize() const
{
1883
  if (args[1]->const_item())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1884
  {
1885 1886 1887 1888 1889 1890
    String* res2= args[1]->val_str((String *)&tmp_value2);

    if (!res2)
      return OPTIMIZE_NONE;

    if (*res2->ptr() != wild_many)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1891
    {
1892
      if (args[0]->result_type() != STRING_RESULT || *res2->ptr() != wild_one)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1893 1894 1895 1896 1897 1898
	return OPTIMIZE_OP;
    }
  }
  return OPTIMIZE_NONE;
}

1899

1900
bool Item_func_like::fix_fields(THD *thd, TABLE_LIST *tlist, Item ** ref)
1901
{
1902
  if (Item_bool_func2::fix_fields(thd, tlist, ref))
1903 1904
    return 1;

1905 1906 1907
  /*
    We could also do boyer-more for non-const items, but as we would have to
    recompute the tables for each row it's not worth it.
1908
  */
1909
  if (args[1]->const_item() && !use_strnxfrm(collation.collation) &&
1910
      !(specialflag & SPECIAL_NO_NEW_FUNC))
1911 1912
  {
    String* res2 = args[1]->val_str(&tmp_value2);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1913 1914 1915
    if (!res2)
      return 0;					// Null argument

1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
    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;
1929
      for (; *tmp != wild_many && *tmp != wild_one && *tmp != escape; tmp++) ;
1930
      canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation);
1931 1932 1933 1934 1935 1936
    }

    if (canDoTurboBM)
    {
      pattern     = first + 1;
      pattern_len = len - 2;
1937 1938 1939 1940 1941
      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;
1942 1943
      turboBM_compute_good_suffix_shifts(suff);
      turboBM_compute_bad_character_shifts();
1944
      DBUG_PRINT("info",("done"));
1945 1946 1947 1948 1949
    }
  }
  return 0;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1950 1951 1952
#ifdef USE_REGEX

bool
1953
Item_func_regex::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1954
{
1955 1956
  if (args[0]->fix_fields(thd, tables, args) || args[0]->check_cols(1) ||
      args[1]->fix_fields(thd,tables, args + 1) || args[1]->check_cols(1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1957 1958
    return 1;					/* purecov: inspected */
  with_sum_func=args[0]->with_sum_func || args[1]->with_sum_func;
1959 1960
  max_length= 1;
  decimals= 0;
1961

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1962
  if (agg_arg_collations(cmp_collation, args, 2))
1963
    return 1;
1964

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1965
  used_tables_cache=args[0]->used_tables() | args[1]->used_tables();
1966 1967
  not_null_tables_cache= (args[0]->not_null_tables() |
			  args[1]->not_null_tables());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1968 1969 1970 1971
  const_item_cache=args[0]->const_item() && args[1]->const_item();
  if (!regex_compiled && args[1]->const_item())
  {
    char buff[MAX_FIELD_WIDTH];
1972
    String tmp(buff,sizeof(buff),&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1973 1974 1975 1976 1977 1978 1979 1980
    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(),
1981 1982
		       (cmp_collation.collation->state & MY_CS_BINSORT) ?
		       REG_EXTENDED | REG_NOSUB :
1983
		       REG_EXTENDED | REG_NOSUB | REG_ICASE,
1984
		       cmp_collation.collation)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
    {
      (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;
1995
  fixed= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1996 1997 1998
  return 0;
}

1999

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2000 2001 2002
longlong Item_func_regex::val_int()
{
  char buff[MAX_FIELD_WIDTH];
2003
  String *res, tmp(buff,sizeof(buff),&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013

  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];
2014
    String *res2, tmp2(buff2,sizeof(buff2),&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2015 2016 2017 2018 2019 2020 2021

    res2= args[1]->val_str(&tmp2);
    if (args[1]->null_value)
    {
      null_value=1;
      return 0;
    }
2022
    if (!regex_compiled || sortcmp(res2,&prev_regexp,&my_charset_bin))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2023 2024 2025 2026 2027 2028 2029 2030
    {
      prev_regexp.copy(*res2);
      if (regex_compiled)
      {
	regfree(&preg);
	regex_compiled=0;
      }
      if (regcomp(&preg,res2->c_ptr(),
2031 2032
		  (cmp_collation.collation->state & MY_CS_BINSORT) ?
		  REG_EXTENDED | REG_NOSUB :
2033
		  REG_EXTENDED | REG_NOSUB | REG_ICASE,
2034
		  cmp_collation.collation))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
      {
	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 */
2057 2058 2059


#ifdef LIKE_CMP_TOUPPER
2060
#define likeconv(cs,A) (uchar) (cs)->toupper(A)
2061
#else
2062
#define likeconv(cs,A) (uchar) (cs)->sort_order[(uchar) (A)]
2063 2064 2065 2066 2067 2068 2069 2070
#endif


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

2071
void Item_func_like::turboBM_compute_suffixes(int *suff)
2072 2073 2074 2075
{
  const int   plm1 = pattern_len - 1;
  int            f = 0;
  int            g = plm1;
2076 2077
  int *const splm1 = suff + plm1;
  CHARSET_INFO	*cs=system_charset_info;	// QQ Needs to be fixed
2078 2079 2080

  *splm1 = pattern_len;

2081
  if (cmp.cmp_collation.collation == &my_charset_bin)
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
  {
    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;
2113
	while (g >= 0 &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2114
	       likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f]))
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
	  g--;
	suff[i] = f - g;
      }
    }
  }
}


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

2128
void Item_func_like::turboBM_compute_good_suffix_shifts(int *suff)
2129 2130 2131
{
  turboBM_compute_suffixes(suff);

2132 2133
  int *end = bmGs + pattern_len;
  int *k;
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
  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++)
      {
2147
	int *tmp2 = bmGs + j;
2148 2149 2150 2151 2152 2153
	if (*tmp2 == pattern_len)
	  *tmp2 = tmp;
      }
    }
  }

2154
  int *tmp2;
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
  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()
{
2175 2176 2177 2178 2179 2180
  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

2181 2182 2183
  for (i = bmBc; i < end; i++)
    *i = pattern_len;

2184
  if (cmp.cmp_collation.collation == &my_charset_bin)
2185
  {
2186
    for (j = 0; j < plm1; j++)
2187
      bmBc[(uint) (uchar) pattern[j]] = plm1 - j;
2188
  }
2189
  else
2190
  {
2191
    for (j = 0; j < plm1; j++)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2192
      bmBc[(uint) likeconv(cs,pattern[j])] = plm1 - j;
2193
  }
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
}


/**********************************************************************
  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;
2209
  CHARSET_INFO	*cs= cmp.cmp_collation.collation;	// QQ Needs to be fixed
2210

2211 2212
  const int plm1=  pattern_len - 1;
  const int tlmpl= text_len - pattern_len;
2213 2214

  /* Searching */
2215
  if (cmp.cmp_collation.collation == &my_charset_bin)
2216 2217 2218
  {
    while (j <= tlmpl)
    {
2219
      register int i= plm1;
2220 2221 2222 2223
      while (i >= 0 && pattern[i] == text[i + j])
      {
	i--;
	if (i == plm1 - shift)
2224
	  i-= u;
2225 2226
      }
      if (i < 0)
2227
	return 1;
2228 2229 2230

      register const int v = plm1 - i;
      turboShift = u - v;
2231
      bcShift    = bmBc[(uint) (uchar) text[i + j]] - plm1 + i;
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
      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;
      }
2242
      j+= shift;
2243
    }
2244
    return 0;
2245 2246 2247 2248 2249 2250
  }
  else
  {
    while (j <= tlmpl)
    {
      register int i = plm1;
2251
      while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
2252 2253 2254
      {
	i--;
	if (i == plm1 - shift)
2255
	  i-= u;
2256 2257
      }
      if (i < 0)
2258
	return 1;
2259 2260 2261

      register const int v = plm1 - i;
      turboShift = u - v;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2262
      bcShift    = bmBc[(uint) likeconv(cs, text[i + j])] - plm1 + i;
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
      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;
      }
2273
      j+= shift;
2274
    }
2275
    return 0;
2276 2277
  }
}
2278

2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299

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

2300 2301 2302 2303 2304
longlong Item_cond_xor::val_int()
{
  List_iterator<Item> li(list);
  Item *item;
  int result=0;	
2305
  null_value=0;
2306 2307
  while ((item=li++))
  {
2308 2309 2310 2311 2312 2313
    result^= (item->val_int() != 0);
    if (item->null_value)
    {
      null_value=1;
      return 0;
    }
2314
  }
2315
  return (longlong) result;
2316
}