item.cc 55.2 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
   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 */


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

#include "mysql_priv.h"
#include <m_ctype.h>
#include "my_dir.h"
25
#include "sp_rcontext.h"
unknown's avatar
unknown committed
26

27 28
static void mark_as_dependent(THD *thd,
			      SELECT_LEX *last, SELECT_LEX *current,
unknown's avatar
unknown committed
29 30
			      Item_ident *item);

unknown's avatar
unknown committed
31 32 33 34 35 36 37 38 39 40 41
/*****************************************************************************
** Item functions
*****************************************************************************/

/* Init all special items */

void item_init(void)
{
  item_user_lock_init();
}

42
Item::Item():
43
  name_length(0), fixed(0)
unknown's avatar
unknown committed
44
{
45
  marker= 0;
46
  maybe_null=null_value=with_sum_func=unsigned_flag=0;
47
  collation.set(default_charset(), DERIVATION_COERCIBLE);
48 49
  name= 0;
  decimals= 0; max_length= 0;
50 51 52 53

  /* Put item in free list so that we can free all items at end */
  THD *thd= current_thd;
  next= thd->free_list;
54
  thd->free_list= this;
55
  /*
56
    Item constructor can be called during execution other then SQL_COM
57
    command => we should check thd->lex->current_select on zero (thd->lex
unknown's avatar
unknown committed
58
    can be uninitialised)
59
  */
unknown's avatar
unknown committed
60
  if (thd->lex->current_select)
61 62
  {
    SELECT_LEX_NODE::enum_parsing_place place= 
unknown's avatar
unknown committed
63
      thd->lex->current_select->parsing_place;
64 65
    if (place == SELECT_LEX_NODE::SELECT_LIST ||
	place == SELECT_LEX_NODE::IN_HAVING)
unknown's avatar
unknown committed
66
      thd->lex->current_select->select_n_having_items++;
67
  }
unknown's avatar
unknown committed
68 69
}

70 71 72 73 74
/*
  Constructor used by Item_field, Item_ref & agregate (sum) functions.
  Used for duplicating lists in processing queries with temporary
  tables
*/
75
Item::Item(THD *thd, Item &item):
76 77 78 79 80 81 82 83 84
  str_value(item.str_value),
  name(item.name),
  max_length(item.max_length),
  marker(item.marker),
  decimals(item.decimals),
  maybe_null(item.maybe_null),
  null_value(item.null_value),
  unsigned_flag(item.unsigned_flag),
  with_sum_func(item.with_sum_func),
unknown's avatar
unknown committed
85
  fixed(item.fixed),
86
  collation(item.collation)
87
{
88
  next= thd->free_list;				// Put in free list
89
  thd->free_list= this;
90 91
}

unknown's avatar
unknown committed
92 93 94 95 96 97

void Item::print_item_w_name(String *str)
{
  print(str);
  if (name)
  {
98
    str->append(" AS `", 5);
unknown's avatar
unknown committed
99 100 101 102 103 104
    str->append(name);
    str->append('`');
  }
}


unknown's avatar
unknown committed
105 106 107 108 109 110 111 112
Item_ident::Item_ident(const char *db_name_par,const char *table_name_par,
		       const char *field_name_par)
  :db_name(db_name_par),table_name(table_name_par),field_name(field_name_par),
   depended_from(0)
{
  name = (char*) field_name_par;
}

113 114 115
// Constructor used by Item_field & Item_ref (see Item comment)
Item_ident::Item_ident(THD *thd, Item_ident &item):
  Item(thd, item),
116 117 118 119 120
  db_name(item.db_name),
  table_name(item.table_name),
  field_name(item.field_name),
  depended_from(item.depended_from)
{}
121

unknown's avatar
unknown committed
122 123 124 125 126
bool Item_ident::remove_dependence_processor(byte * arg)
{
  DBUG_ENTER("Item_ident::remove_dependence_processor");
  if (depended_from == (st_select_lex *) arg)
    depended_from= 0;
127
  DBUG_RETURN(0);
unknown's avatar
unknown committed
128 129 130
}


unknown's avatar
unknown committed
131 132 133 134
bool Item::check_cols(uint c)
{
  if (c != 1)
  {
unknown's avatar
unknown committed
135
    my_error(ER_OPERAND_COLUMNS, MYF(0), c);
unknown's avatar
unknown committed
136 137 138 139 140
    return 1;
  }
  return 0;
}

unknown's avatar
unknown committed
141 142

void Item::set_name(const char *str, uint length, CHARSET_INFO *cs)
unknown's avatar
unknown committed
143 144 145
{
  if (!length)
  {
unknown's avatar
unknown committed
146 147
    /* Empty string, used by AS or internal function like last_insert_id() */
    name= (char*) str;
148
    name_length= 0;
unknown's avatar
unknown committed
149 150 151 152 153 154
    return;
  }
  while (length && !my_isgraph(cs,*str))
  {						// Fix problem with yacc
    length--;
    str++;
unknown's avatar
unknown committed
155
  }
unknown's avatar
unknown committed
156 157 158
  if (!my_charset_same(cs, system_charset_info))
  {
    uint32 res_length;
159
    name= sql_strmake_with_convert(str, name_length= length, cs,
unknown's avatar
unknown committed
160 161 162 163
				   MAX_ALIAS_NAME, system_charset_info,
				   &res_length);
  }
  else
164
    name= sql_strmake(str, (name_length= min(length,MAX_ALIAS_NAME)));
unknown's avatar
unknown committed
165 166
}

unknown's avatar
unknown committed
167

168
/*
169 170 171
  This function is called when:
  - Comparing items in the WHERE clause (when doing where optimization)
  - When trying to find an ORDER BY/GROUP BY item in the SELECT part
172 173 174
*/

bool Item::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
175 176
{
  return type() == item->type() && name && item->name &&
177
    !my_strcasecmp(system_charset_info,name,item->name);
unknown's avatar
unknown committed
178 179
}

180 181 182 183 184
bool Item_string::eq(const Item *item, bool binary_cmp) const
{
  if (type() == item->type())
  {
    if (binary_cmp)
185
      return !sortcmp(&str_value, &item->str_value, &my_charset_bin);
186
    return !sortcmp(&str_value, &item->str_value, collation.collation);
187 188 189 190 191
  }
  return 0;
}


unknown's avatar
unknown committed
192 193 194 195 196
/*
  Get the value of the function as a TIME structure.
  As a extra convenience the time structure is reset on error!
 */

197
bool Item::get_date(TIME *ltime,uint fuzzydate)
unknown's avatar
unknown committed
198 199
{
  char buff[40];
unknown's avatar
unknown committed
200
  String tmp(buff,sizeof(buff), &my_charset_bin),*res;
unknown's avatar
unknown committed
201
  if (!(res=val_str(&tmp)) ||
202 203
      str_to_TIME(res->ptr(),res->length(),ltime,fuzzydate) <= 
      TIMESTAMP_DATETIME_ERROR)
unknown's avatar
unknown committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

/*
  Get time of first argument.
  As a extra convenience the time structure is reset on error!
 */

bool Item::get_time(TIME *ltime)
{
  char buff[40];
unknown's avatar
unknown committed
219
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
unknown's avatar
unknown committed
220
  if (!(res=val_str(&tmp)) ||
221
      str_to_time(res->ptr(),res->length(),ltime))
unknown's avatar
unknown committed
222 223 224 225 226 227 228
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

229
CHARSET_INFO * Item::default_charset() const
230
{
unknown's avatar
unknown committed
231
  return current_thd->variables.collation_connection;
232 233
}

234 235 236 237 238 239 240

Item *
Item_splocal::this_item()
{
  THD *thd= current_thd;

  return thd->spcont->get_item(m_offset);
241 242
}

243 244 245 246 247 248 249 250
Item *
Item_splocal::this_const_item() const
{
  THD *thd= current_thd;

  return thd->spcont->get_item(m_offset);
}

251 252 253 254 255 256 257 258 259 260 261
Item::Type
Item_splocal::type() const
{
  THD *thd= current_thd;

  if (thd->spcont)
    return thd->spcont->get_item(m_offset)->type();
  return NULL_ITEM;		// Anything but SUBSELECT_ITEM
}


262
bool DTCollation::aggregate(DTCollation &dt)
263
{
264
  if (!my_charset_same(collation, dt.collation))
265
  {
266 267 268
    /* 
       We do allow to use binary strings (like BLOBS)
       together with character strings.
unknown's avatar
unknown committed
269 270
       Binaries have more precedance than a character
       string of the same derivation.
271
    */
272
    if (collation == &my_charset_bin)
273
    {
274 275 276 277
      if (derivation <= dt.derivation)
	; // Do nothing
      else
	set(dt);
278
    }
279
    else if (dt.collation == &my_charset_bin)
280
    {
281 282 283 284
      if (dt.derivation <= derivation)
        set(dt);
      else
       ; // Do nothing
285 286 287 288 289 290
    }
    else
    {
      set(0, DERIVATION_NONE);
      return 1; 
    }
291
  }
292
  else if (derivation < dt.derivation)
293
  {
294
    // Do nothing
295
  }
296
  else if (dt.derivation < derivation)
297
  {
298
    set(dt);
299
  }
300 301 302
  else
  { 
    if (collation == dt.collation)
303
    {
304 305 306 307 308
      // Do nothing
    }
    else 
    {
      if (derivation == DERIVATION_EXPLICIT)
309
      {
310 311
	set(0, DERIVATION_NONE);
	return 1;
312
      }
313 314 315
      CHARSET_INFO *bin= get_charset_by_csname(collation->csname, 
					       MY_CS_BINSORT,MYF(0));
      set(bin, DERIVATION_NONE);
316
    }
317 318 319 320
  }
  return 0;
}

321 322
Item_field::Item_field(Field *f)
  :Item_ident(NullS,f->table_name,f->field_name), item_equal(0)
unknown's avatar
unknown committed
323 324
{
  set_field(f);
325
  collation.set(DERIVATION_IMPLICIT);
326
  fixed= 1; // This item is not needed in fix_fields
unknown's avatar
unknown committed
327 328
}

329
// Constructor need to process subselect with temporary tables (see Item)
330 331 332 333 334 335
Item_field::Item_field(THD *thd, Item_field &item)
  :Item_ident(thd, item),
   field(item.field),
   result_field(item.result_field)
{
  collation.set(DERIVATION_IMPLICIT);
336
  item_equal= item.item_equal;
337
}
unknown's avatar
unknown committed
338 339 340 341 342 343 344 345 346

void Item_field::set_field(Field *field_par)
{
  field=result_field=field_par;			// for easy coding with fields
  maybe_null=field->maybe_null();
  max_length=field_par->field_length;
  decimals= field->decimals();
  table_name=field_par->table_name;
  field_name=field_par->field_name;
347
  db_name=field_par->table->table_cache_key;
348
  unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
349
  collation.set(field_par->charset(), DERIVATION_IMPLICIT);
unknown's avatar
unknown committed
350 351 352 353 354
}

const char *Item_ident::full_name() const
{
  char *tmp;
355
  if (!table_name || !field_name)
unknown's avatar
unknown committed
356
    return field_name ? field_name : name ? name : "tmp_field";
unknown's avatar
unknown committed
357
  if (db_name && db_name[0])
unknown's avatar
unknown committed
358
  {
unknown's avatar
unknown committed
359 360
    tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
			  (uint) strlen(field_name)+3);
unknown's avatar
unknown committed
361 362 363 364
    strxmov(tmp,db_name,".",table_name,".",field_name,NullS);
  }
  else
  {
unknown's avatar
unknown committed
365 366
    tmp=(char*) sql_alloc((uint) strlen(table_name)+
			  (uint) strlen(field_name)+2);
unknown's avatar
unknown committed
367 368 369 370 371 372 373 374 375 376
    strxmov(tmp,table_name,".",field_name,NullS);
  }
  return tmp;
}

/* ARGSUSED */
String *Item_field::val_str(String *str)
{
  if ((null_value=field->is_null()))
    return 0;
377
  str->set_charset(str_value.charset());
unknown's avatar
unknown committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  return field->val_str(str,&str_value);
}

double Item_field::val()
{
  if ((null_value=field->is_null()))
    return 0.0;
  return field->val_real();
}

longlong Item_field::val_int()
{
  if ((null_value=field->is_null()))
    return 0;
  return field->val_int();
}


String *Item_field::str_result(String *str)
{
  if ((null_value=result_field->is_null()))
    return 0;
400
  str->set_charset(str_value.charset());
unknown's avatar
unknown committed
401 402 403
  return result_field->val_str(str,&str_value);
}

404
bool Item_field::get_date(TIME *ltime,uint fuzzydate)
unknown's avatar
unknown committed
405 406 407 408 409 410 411 412 413
{
  if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

414
bool Item_field::get_date_result(TIME *ltime,uint fuzzydate)
415 416 417 418 419 420 421 422 423 424
{
  if ((null_value=result_field->is_null()) ||
      result_field->get_date(ltime,fuzzydate))
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

unknown's avatar
unknown committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
bool Item_field::get_time(TIME *ltime)
{
  if ((null_value=field->is_null()) || field->get_time(ltime))
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

double Item_field::val_result()
{
  if ((null_value=result_field->is_null()))
    return 0.0;
  return result_field->val_real();
}

longlong Item_field::val_int_result()
{
  if ((null_value=result_field->is_null()))
    return 0;
  return result_field->val_int();
}

449

450
bool Item_field::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
451
{
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  if (item->type() != FIELD_ITEM)
    return 0;
  
  Item_field *item_field= (Item_field*) item;
  if (item_field->field)
    return item_field->field == field;
  /*
    We may come here when we are trying to find a function in a GROUP BY
    clause from the select list.
    In this case the '100 % correct' way to do this would be to first
    run fix_fields() on the GROUP BY item and then retry this function, but
    I think it's better to relax the checking a bit as we will in
    most cases do the correct thing by just checking the field name.
    (In cases where we would choose wrong we would have to generate a
    ER_NON_UNIQ_ERROR).
  */
  return (!my_strcasecmp(system_charset_info, item_field->name,
			 field_name) &&
	  (!item_field->table_name ||
	   (!my_strcasecmp(table_alias_charset, item_field->table_name,
			   table_name) &&
	    (!item_field->db_name ||
	     (item_field->db_name && !my_strcasecmp(table_alias_charset,
						    item_field->db_name,
						    db_name))))));
unknown's avatar
unknown committed
477 478
}

479

unknown's avatar
unknown committed
480 481 482 483
table_map Item_field::used_tables() const
{
  if (field->table->const_table)
    return 0;					// const item
unknown's avatar
unknown committed
484
  return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
unknown's avatar
unknown committed
485 486
}

487

488
Item *Item_field::get_tmp_table_item(THD *thd)
489
{
490
  Item_field *new_item= new Item_field(thd, *this);
491 492 493 494
  if (new_item)
    new_item->field= new_item->result_field;
  return new_item;
}
unknown's avatar
unknown committed
495

496

unknown's avatar
unknown committed
497 498
String *Item_int::val_str(String *str)
{
unknown's avatar
unknown committed
499
  str->set(value, &my_charset_bin);
unknown's avatar
unknown committed
500 501 502 503 504
  return str;
}

void Item_int::print(String *str)
{
unknown's avatar
unknown committed
505 506
  // my_charset_bin is good enough for numbers
  str_value.set(value, &my_charset_bin);
unknown's avatar
unknown committed
507
  str->append(str_value);
unknown's avatar
unknown committed
508 509
}

510

unknown's avatar
unknown committed
511 512
String *Item_uint::val_str(String *str)
{
unknown's avatar
unknown committed
513
  str->set((ulonglong) value, &my_charset_bin);
unknown's avatar
unknown committed
514 515 516
  return str;
}

517

unknown's avatar
unknown committed
518 519
void Item_uint::print(String *str)
{
520
  // latin1 is good enough for numbers
unknown's avatar
unknown committed
521 522
  str_value.set((ulonglong) value, default_charset());
  str->append(str_value);
unknown's avatar
unknown committed
523 524
}

unknown's avatar
unknown committed
525 526 527

String *Item_real::val_str(String *str)
{
unknown's avatar
unknown committed
528
  str->set(value,decimals,&my_charset_bin);
unknown's avatar
unknown committed
529 530 531
  return str;
}

532

unknown's avatar
unknown committed
533 534
void Item_string::print(String *str)
{
535 536
  str->append('_');
  str->append(collation.collation->csname);
unknown's avatar
unknown committed
537
  str->append('\'');
unknown's avatar
unknown committed
538
  str_value.print(str);
unknown's avatar
unknown committed
539 540 541
  str->append('\'');
}

542 543
bool Item_null::eq(const Item *item, bool binary_cmp) const
{ return item->type() == type(); }
unknown's avatar
unknown committed
544 545 546 547 548 549 550
double Item_null::val() { null_value=1; return 0.0; }
longlong Item_null::val_int() { null_value=1; return 0; }
/* ARGSUSED */
String *Item_null::val_str(String *str)
{ null_value=1; return 0;}


unknown's avatar
unknown committed
551 552
/* Item_param related */
void Item_param::set_null()
553 554
{
  DBUG_ENTER("Item_param::set_null");
555
  maybe_null= null_value= value_is_set= 1;
556
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
557 558 559
}

void Item_param::set_int(longlong i)
560 561 562 563
{
  DBUG_ENTER("Item_param::set_int");
  int_value= (longlong)i;
  item_type= INT_ITEM;
564
  value_is_set= 1;
565 566
  DBUG_PRINT("info", ("integer: %lld", int_value));
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
567 568
}

569
void Item_param::set_double(double value)
570 571
{
  DBUG_ENTER("Item_param::set_double");
unknown's avatar
unknown committed
572
  real_value=value;
573
  item_type= REAL_ITEM;
574
  value_is_set= 1;
575 576
  DBUG_PRINT("info", ("double: %lg", real_value));
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
577 578 579
}


unknown's avatar
unknown committed
580
void Item_param::set_value(const char *str, uint length)
581 582 583 584
{
  DBUG_ENTER("Item_param::set_value");
  str_value.copy(str,length,default_charset());
  item_type= STRING_ITEM;
585
  value_is_set= 1;
586 587
  DBUG_PRINT("info", ("string: %s", str_value.ptr()));
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
588 589
}

590

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
void Item_param::set_time(TIME *tm, timestamp_type type)
{ 
  ltime.year= tm->year;
  ltime.month= tm->month;
  ltime.day= tm->day;
  
  ltime.hour= tm->hour;
  ltime.minute= tm->minute;
  ltime.second= tm->second; 

  ltime.second_part= tm->second_part;

  ltime.time_type= type;
  
  item_is_time= true;
  item_type= STRING_ITEM;
607
  value_is_set= 1;
608 609 610
}


unknown's avatar
unknown committed
611 612 613 614
void Item_param::set_longdata(const char *str, ulong length)
{  
  str_value.append(str,length);
  long_data_supplied= 1;
615
  value_is_set= 1;
unknown's avatar
unknown committed
616 617 618
}


unknown's avatar
unknown committed
619
int Item_param::save_in_field(Field *field, bool no_conversions)
unknown's avatar
unknown committed
620
{
unknown's avatar
unknown committed
621 622
  THD *thd= current_thd;

unknown's avatar
unknown committed
623
  DBUG_ASSERT(thd->command == COM_EXECUTE);
unknown's avatar
unknown committed
624
  
unknown's avatar
unknown committed
625
  if (null_value)
626
    return (int) set_field_to_null(field);   
unknown's avatar
unknown committed
627 628 629 630 631
    
  field->set_notnull();
  if (item_result_type == INT_RESULT)
  {
    longlong nr=val_int();
632
    return (field->store(nr)) ? -1 : 0;
unknown's avatar
unknown committed
633 634 635 636
  }
  if (item_result_type == REAL_RESULT)
  {
    double nr=val();    
637
    return (field->store(nr)) ? -1 : 0; 
638 639 640 641 642
  }  
  if (item_is_time)
  {
    field->store_time(&ltime, ltime.time_type);
    return 0;
unknown's avatar
unknown committed
643
  }
unknown's avatar
unknown committed
644 645
  String *result=val_str(&str_value);
  return (field->store(result->ptr(),result->length(),field->charset())) ? -1 : 0;
unknown's avatar
unknown committed
646 647
}

648 649 650 651 652
bool Item_param::get_time(TIME *res)
{
  *res=ltime;
  return 0;
}
653

unknown's avatar
unknown committed
654 655
double Item_param::val() 
{
656
  int err;
657
  switch (item_result_type) {
unknown's avatar
unknown committed
658
  case STRING_RESULT:
659
    return (double) my_strntod(str_value.charset(), (char*) str_value.ptr(),
660
			       str_value.length(), (char**) 0, &err); 
unknown's avatar
unknown committed
661 662 663 664 665 666 667
  case INT_RESULT:
    return (double)int_value;
  default:
    return real_value;
  }
} 

668

unknown's avatar
unknown committed
669 670
longlong Item_param::val_int() 
{ 
671
 int err;
672
 switch (item_result_type) {
unknown's avatar
unknown committed
673
  case STRING_RESULT:
674 675 676
    return my_strntoll(str_value.charset(),
		       str_value.ptr(),str_value.length(),10,
		       (char**) 0,&err);
unknown's avatar
unknown committed
677 678 679 680 681 682 683
  case REAL_RESULT:
    return (longlong) (real_value+(real_value > 0 ? 0.5 : -0.5));
  default:
    return int_value;
  }
}

684

unknown's avatar
unknown committed
685 686
String *Item_param::val_str(String* str) 
{ 
687
  switch (item_result_type) {
unknown's avatar
unknown committed
688
  case INT_RESULT:
unknown's avatar
unknown committed
689
    str->set(int_value, &my_charset_bin);
unknown's avatar
unknown committed
690 691
    return str;
  case REAL_RESULT:
unknown's avatar
unknown committed
692
    str->set(real_value, 2, &my_charset_bin);
unknown's avatar
unknown committed
693 694 695 696 697
    return str;
  default:
    return (String*) &str_value;
  }
}
698 699 700 701 702 703 704 705 706 707 708

/*
  Return Param item values in string format, for generating the dynamic 
  query used in update/binary logs
*/

String *Item_param::query_val_str(String* str) 
{ 
  switch (item_result_type) {
  case INT_RESULT:
  case REAL_RESULT:
709
    return val_str(str);
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    break;
  default:
    str->set("'", 1, default_charset());
    
    if (!item_is_time)
    {
      str->append(str_value);
      const char *from= str->ptr(); 
      uint32 length= 1;
      
      // Escape misc cases
      char *to= (char *)from, *end= (char *)to+str->length(); 
      for (to++; to != end ; length++, to++)
      {
        switch(*to) {
          case '\'':
          case '"':  
          case '\r':
          case '\n':
          case '\\': // TODO: Add remaining ..
            str->replace(length,0,"\\",1); 
            to++; end++; length++;
            break;
          default:     
            break;
        }
      }
    }
    else
    {
740 741
      char buff[40];
      String tmp(buff,sizeof(buff), &my_charset_bin);
742 743
      
      switch (ltime.time_type)  {
744 745 746 747 748 749 750 751 752 753 754 755 756
      case TIMESTAMP_NONE:
      case TIMESTAMP_DATETIME_ERROR:
	tmp.length(0);				// Should never happen
	break;
      case TIMESTAMP_DATE:
	make_date((DATE_TIME_FORMAT*) 0, &ltime, &tmp);
	break;
      case TIMESTAMP_DATETIME:
	make_datetime((DATE_TIME_FORMAT*) 0, &ltime, &tmp);
	break;
      case TIMESTAMP_TIME:
	make_time((DATE_TIME_FORMAT*) 0, &ltime, &tmp);
	break;
757
      }
758
      str->append(tmp);
759
    }
760
    str->append('\'');
761 762 763
  }
  return str;
}
unknown's avatar
unknown committed
764 765
/* End of Item_param related */

766

unknown's avatar
unknown committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
void Item_copy_string::copy()
{
  String *res=item->val_str(&str_value);
  if (res && res != &str_value)
    str_value.copy(*res);
  null_value=item->null_value;
}

/* ARGSUSED */
String *Item_copy_string::val_str(String *str)
{
  if (null_value)
    return (String*) 0;
  return &str_value;
}

/*
784
  Functions to convert item to field (for send_fields)
unknown's avatar
unknown committed
785 786 787 788
*/

/* ARGSUSED */
bool Item::fix_fields(THD *thd,
unknown's avatar
unknown committed
789 790
		      struct st_table_list *list,
		      Item ** ref)
unknown's avatar
unknown committed
791
{
792
  fixed= 1;
unknown's avatar
unknown committed
793 794 795
  return 0;
}

796 797 798
double Item_ref_null_helper::val()
{
  double tmp= (*ref)->val_result();
unknown's avatar
unknown committed
799
  owner->was_null|= null_value= (*ref)->null_value;
800 801 802 803 804
  return tmp;
}
longlong Item_ref_null_helper::val_int()
{
  longlong tmp= (*ref)->val_int_result();
unknown's avatar
unknown committed
805
  owner->was_null|= null_value= (*ref)->null_value;
806 807 808 809 810
  return tmp;
}
String* Item_ref_null_helper::val_str(String* s)
{
  String* tmp= (*ref)->str_result(s);
unknown's avatar
unknown committed
811
  owner->was_null|= null_value= (*ref)->null_value;
812 813
  return tmp;
}
814
bool Item_ref_null_helper::get_date(TIME *ltime, uint fuzzydate)
815 816 817
{  
  return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate));
}
unknown's avatar
unknown committed
818

unknown's avatar
unknown committed
819 820 821 822 823 824

/*
  Mark item and SELECT_LEXs as dependent if it is not outer resolving

  SYNOPSIS
    mark_as_dependent()
825
    thd - thread handler
unknown's avatar
unknown committed
826 827 828 829 830
    last - select from which current item depend
    current  - current select
    item - item which should be marked
*/

831
static void mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current,
unknown's avatar
unknown committed
832 833
			      Item_ident *item)
{
unknown's avatar
unknown committed
834 835 836
  // store pointer on SELECT_LEX from wich item is dependent
  item->depended_from= last;
  current->mark_as_dependent(last);
unknown's avatar
unknown committed
837
  if (thd->lex->describe & DESCRIBE_EXTENDED)
838 839 840 841 842 843 844 845 846 847
  {
    char warn_buff[MYSQL_ERRMSG_SIZE];
    sprintf(warn_buff, ER(ER_WARN_FIELD_RESOLVED),
	    (item->db_name?item->db_name:""), (item->db_name?".":""),
	    (item->table_name?item->table_name:""), (item->table_name?".":""),
	    item->field_name,
	    current->select_number, last->select_number);
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
		 ER_WARN_FIELD_RESOLVED, warn_buff);
  }
unknown's avatar
unknown committed
848 849 850
}


unknown's avatar
unknown committed
851
bool Item_field::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
unknown's avatar
unknown committed
852
{
853
  if (!field)					// If field is not checked
unknown's avatar
unknown committed
854
  {
855
    TABLE_LIST *where= 0;
856
    bool upward_lookup= 0;
857
    Field *tmp= (Field *)not_found_field;
unknown's avatar
unknown committed
858
    if ((tmp= find_field_in_tables(thd, this, tables, &where, 0)) ==
859
	not_found_field)
860 861
    {
      /*
862
	We can't find table field in table list of current select,
863
	consequently we have to find it in outer subselect(s).
864 865 866
	We can't join lists of outer & current select, because of scope
	of view rules. For example if both tables (outer & current) have
	field 'field' it is not mistake to refer to this field without
867 868 869
	mention of table name, but if we join tables in one list it will
	cause error ER_NON_UNIQ_ERROR in find_field_in_tables.
      */
unknown's avatar
unknown committed
870
      SELECT_LEX *last= 0;
unknown's avatar
unknown committed
871 872 873
#ifdef EMBEDDED_LIBRARY
      thd->net.last_errno= 0;
#endif
874
      TABLE_LIST *table_list;
875
      Item **refer= (Item **)not_found_item;
876
      uint counter;
877
      // Prevent using outer fields in subselects, that is not supported now
878
      SELECT_LEX *cursel= (SELECT_LEX *) thd->lex->current_select;
unknown's avatar
unknown committed
879
      if (cursel->master_unit()->first_select()->linkage != DERIVED_TABLE_TYPE)
880 881 882
      {
	SELECT_LEX_UNIT *prev_unit= cursel->master_unit();
	for (SELECT_LEX *sl= prev_unit->outer_select();
883
	     sl;
884
	     sl= (prev_unit= sl->master_unit())->outer_select())
885
	{
886
	  upward_lookup= 1;
887
	  table_list= (last= sl)->get_table_list();
888
	  if (sl->resolve_mode == SELECT_LEX::INSERT_MODE && table_list)
889 890 891 892
	  {
	    // it is primary INSERT st_select_lex => skip first table resolving
	    table_list= table_list->next;
	  }
unknown's avatar
unknown committed
893 894

	  Item_subselect *prev_subselect_item= prev_unit->item;
895
	  if ((tmp= find_field_in_tables(thd, this,
896
					 table_list, &where,
897
					 0)) != not_found_field)
898
	  {
unknown's avatar
unknown committed
899 900
	    prev_subselect_item->used_tables_cache|= tmp->table->map;
	    prev_subselect_item->const_item_cache= 0;
901
	    break;
902
	  }
903
	  if (sl->resolve_mode == SELECT_LEX::SELECT_MODE &&
904 905
	      (refer= find_item_in_list(this, sl->item_list, &counter,
					 REPORT_EXCEPT_NOT_FOUND)) !=
906
	       (Item **) not_found_item)
907 908 909
	  {
	    if (*refer && (*refer)->fixed) // Avoid crash in case of error
	    {
unknown's avatar
unknown committed
910 911
	      prev_subselect_item->used_tables_cache|= (*refer)->used_tables();
	      prev_subselect_item->const_item_cache&= (*refer)->const_item();
912
	    }
913
	    break;
914 915 916
	  }

	  // Reference is not found => depend from outer (or just error)
unknown's avatar
unknown committed
917 918
	  prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
	  prev_subselect_item->const_item_cache= 0;
919

920 921
	  if (sl->master_unit()->first_select()->linkage ==
	      DERIVED_TABLE_TYPE)
922
	    break; // do not look over derived table
923
	}
924
      }
925
      if (!tmp)
926
	return -1;
927 928 929
      else if (!refer)
	return 1;
      else if (tmp == not_found_field && refer == (Item **)not_found_item)
unknown's avatar
unknown committed
930
      {
931
	if (upward_lookup)
unknown's avatar
unknown committed
932
	{
933 934 935
	  // We can't say exactly what absend table or field
	  my_printf_error(ER_BAD_FIELD_ERROR, ER(ER_BAD_FIELD_ERROR), MYF(0),
			  full_name(), thd->where);
unknown's avatar
unknown committed
936
	}
937
	else
unknown's avatar
unknown committed
938
	{
939 940
	  // Call to report error
	  find_field_in_tables(thd, this, tables, &where, 1);
unknown's avatar
unknown committed
941
	}
unknown's avatar
unknown committed
942 943
	return -1;
      }
944 945
      else if (refer != (Item **)not_found_item)
      {
946 947 948 949 950 951 952
	if (!(*refer)->fixed)
	{
	  my_error(ER_ILLEGAL_REFERENCE, MYF(0), name,
		   "forward reference in item list");
	  return -1;
	}

unknown's avatar
unknown committed
953 954 955 956 957
	Item_ref *rf;
	*ref= rf= new Item_ref(last->ref_pointer_array + counter,
			       (char *)table_name,
			       (char *)field_name);
	if (!rf)
958
	  return 1;
unknown's avatar
unknown committed
959
	if (rf->fix_fields(thd, tables, ref) || rf->check_cols(1))
unknown's avatar
unknown committed
960
	  return 1;
unknown's avatar
unknown committed
961

962
	mark_as_dependent(thd, last, cursel, rf);
963 964
	return 0;
      }
965
      else
unknown's avatar
unknown committed
966
      {
967
	mark_as_dependent(thd, last, cursel, this);
unknown's avatar
unknown committed
968
	if (last->having_fix_field)
969 970 971 972 973 974 975
	{
	  Item_ref *rf;
	  *ref= rf= new Item_ref((where->db[0]?where->db:0), 
				 (char *)where->alias,
				 (char *)field_name);
	  if (!rf)
	    return 1;
unknown's avatar
unknown committed
976
	  return rf->fix_fields(thd, tables, ref) ||  rf->check_cols(1);
977
	}
unknown's avatar
unknown committed
978
      }
979
    }
980 981 982
    else if (!tmp)
      return -1;

unknown's avatar
unknown committed
983 984
    set_field(tmp);
  }
unknown's avatar
unknown committed
985
  else if (thd->set_query_id && field->query_id != thd->query_id)
986 987 988 989 990
  {
    /* We only come here in unions */
    TABLE *table=field->table;
    field->query_id=thd->query_id;
    table->used_fields++;
991
    table->used_keys.intersect(field->part_of_key);
992
  }
993
  fixed= 1;
unknown's avatar
unknown committed
994 995 996
  return 0;
}

unknown's avatar
unknown committed
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

/*
  Find a field among specified multiple equalities 

  SYNOPSIS
    find_item_equal()
    cond_equal   reference to list of multiple equalities where
                 the field (this object) is to be looked for
  
  DESCRIPTION
    The function first searches the field among multiple equalities
    of the current level (in the cond_equal->current_level list).
    If it fails, it continues searching in upper levels accessed
    through a pointer cond_equal->upper_levels.
    The search terminates as soon as a multiple equality containing 
    the field is found. 

  RETURN VALUES
    First Item_equal containing the field, if success
    0, otherwise
*/

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal)
{
  Item_equal *item= 0;
  while (cond_equal)
  {
    List_iterator_fast<Item_equal> li(cond_equal->current_level);
    while ((item= li++))
    {
      if (item->contains(field))
        return item;
    }
unknown's avatar
unknown committed
1030 1031 1032 1033 1034
    /* 
      The field is not found in any of the multiple equalities
      of the current level. Look for it in upper levels
    */
    cond_equal= cond_equal->upper_levels;
1035
  }
unknown's avatar
unknown committed
1036
  return 0;
1037 1038
}

unknown's avatar
unknown committed
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

/*
  Set a pointer to the multiple equality the field reference belongs to (if any)
   
  SYNOPSIS
    equal_fields_propagator()
    arg - reference to list of multiple equalities where
          the field (this object) is to be looked for
  
  DESCRIPTION
    The function looks for a multiple equality containing the field item
    among those referenced by arg.
    In the case such equality exists the function does the following.
    If the found multiple equality contains a constant, then the field
    reference is substituted for this constant, otherwise it sets a pointer
    to the multiple equality in the field item.

  NOTES
    This function is supposed to be called as a callback parameter in calls
    of the transform method.  

  RETURN VALUES
    pointer to the replacing constant item, if the field item was substituted 
    pointer to the field item, otherwise.
*/

1065 1066
Item *Item_field::equal_fields_propagator(byte *arg)
{
unknown's avatar
unknown committed
1067
  item_equal= find_item_equal((COND_EQUAL *) arg);
1068 1069 1070
  Item *item= 0;
  if (item_equal)
    item= item_equal->get_const();
unknown's avatar
unknown committed
1071
  if (!item)
1072 1073 1074 1075
    item= this;
  return item;
}

unknown's avatar
unknown committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099

/*
  Set a pointer to the multiple equality the field reference belongs to (if any)
   
  SYNOPSIS
    replace_equal_field_processor()
    arg - a dummy parameter, is not used here
  
  DESCRIPTION
    The function replaces a pointer to a field in the Item_field object
    by a pointer to another field.
    The replacement field is taken from the very beginning of
    the item_equal list which the Item_field object refers to (belongs to)  
    If the Item_field object does not refer any Item_equal object,
    nothing is done.

  NOTES
    This function is supposed to be called as a callback parameter in calls
    of the walk method.  

  RETURN VALUES
    0 
*/

1100 1101 1102 1103 1104
bool Item_field::replace_equal_field_processor(byte *arg)
{
  if (item_equal)
  {
    Item_field *subst= item_equal->get_first();
unknown's avatar
unknown committed
1105
    if (!field->eq(subst->field))
1106 1107 1108 1109 1110 1111 1112
    {
      field= subst->field;
      return 0;
    }
  }
  return 0;
}
unknown's avatar
unknown committed
1113 1114 1115

void Item::init_make_field(Send_field *tmp_field,
			   enum enum_field_types field_type)
1116
{
1117
  char *empty_name= (char*) "";
1118
  tmp_field->db_name=		empty_name;
1119 1120 1121 1122
  tmp_field->org_table_name=	empty_name;
  tmp_field->org_col_name=	empty_name;
  tmp_field->table_name=	empty_name;
  tmp_field->col_name=		name;
1123
  tmp_field->charsetnr=         collation.collation->number;
unknown's avatar
unknown committed
1124 1125 1126 1127
  tmp_field->flags=maybe_null ? 0 : NOT_NULL_FLAG;
  tmp_field->type=field_type;
  tmp_field->length=max_length;
  tmp_field->decimals=decimals;
1128 1129
  if (unsigned_flag)
    tmp_field->flags |= UNSIGNED_FLAG;
unknown's avatar
unknown committed
1130 1131
}

1132
void Item::make_field(Send_field *tmp_field)
unknown's avatar
unknown committed
1133
{
1134
  init_make_field(tmp_field, field_type());
unknown's avatar
unknown committed
1135 1136 1137
}


1138 1139 1140 1141 1142
void Item_empty_string::make_field(Send_field *tmp_field)
{
  init_make_field(tmp_field,FIELD_TYPE_VAR_STRING);
}

unknown's avatar
unknown committed
1143

1144
enum_field_types Item::field_type() const
unknown's avatar
unknown committed
1145
{
1146 1147 1148
  return ((result_type() == STRING_RESULT) ? FIELD_TYPE_VAR_STRING :
	  (result_type() == INT_RESULT) ? FIELD_TYPE_LONGLONG :
	  FIELD_TYPE_DOUBLE);
unknown's avatar
unknown committed
1149 1150
}

1151

1152 1153
Field *Item::tmp_table_field_from_field_type(TABLE *table)
{
1154 1155 1156 1157 1158 1159
  /*
    The field functions defines a field to be not null if null_ptr is not 0
  */
  uchar *null_ptr= maybe_null ? (uchar*) "" : 0;

  switch (field_type()) {
1160
  case MYSQL_TYPE_DECIMAL:
1161 1162
    return new Field_decimal((char*) 0, max_length, null_ptr, 0, Field::NONE,
			     name, table, decimals, 0, unsigned_flag);
1163
  case MYSQL_TYPE_TINY:
1164 1165
    return new Field_tiny((char*) 0, max_length, null_ptr, 0, Field::NONE,
			  name, table, 0, unsigned_flag);
1166
  case MYSQL_TYPE_SHORT:
1167 1168
    return new Field_short((char*) 0, max_length, null_ptr, 0, Field::NONE,
			   name, table, 0, unsigned_flag);
1169
  case MYSQL_TYPE_LONG:
1170 1171
    return new Field_long((char*) 0, max_length, null_ptr, 0, Field::NONE,
			  name, table, 0, unsigned_flag);
1172 1173
#ifdef HAVE_LONG_LONG
  case MYSQL_TYPE_LONGLONG:
1174 1175
    return new Field_longlong((char*) 0, max_length, null_ptr, 0, Field::NONE,
			      name, table, 0, unsigned_flag);
1176
#endif
1177 1178 1179 1180 1181 1182 1183 1184 1185
  case MYSQL_TYPE_FLOAT:
    return new Field_float((char*) 0, max_length, null_ptr, 0, Field::NONE,
			   name, table, decimals, 0, unsigned_flag);
  case MYSQL_TYPE_DOUBLE:
    return new Field_double((char*) 0, max_length, null_ptr, 0, Field::NONE,
			    name, table, decimals, 0, unsigned_flag);
  case MYSQL_TYPE_NULL:
    return new Field_null((char*) 0, max_length, Field::NONE,
			  name, table, &my_charset_bin);
1186 1187
  case MYSQL_TYPE_NEWDATE:
  case MYSQL_TYPE_INT24:
1188 1189
    return new Field_medium((char*) 0, max_length, null_ptr, 0, Field::NONE,
			    name, table, 0, unsigned_flag);
1190 1191 1192 1193 1194 1195 1196 1197
  case MYSQL_TYPE_DATE:
    return new Field_date(maybe_null, name, table, &my_charset_bin);
  case MYSQL_TYPE_TIME:
    return new Field_time(maybe_null, name, table, &my_charset_bin);
  case MYSQL_TYPE_TIMESTAMP:
  case MYSQL_TYPE_DATETIME:
    return new Field_datetime(maybe_null, name, table, &my_charset_bin);
  case MYSQL_TYPE_YEAR:
1198 1199 1200 1201 1202 1203
    return new Field_year((char*) 0, max_length, null_ptr, 0, Field::NONE,
			  name, table);
  default:
    /* This case should never be choosen */
    DBUG_ASSERT(0);
    /* If something goes awfully wrong, it's better to get a string than die */
1204 1205
  case MYSQL_TYPE_ENUM:
  case MYSQL_TYPE_SET:
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
  case MYSQL_TYPE_VAR_STRING:
    if (max_length > 255)
      break;					// If blob
    return new Field_varstring(max_length, maybe_null, name, table,
			       collation.collation);
  case MYSQL_TYPE_STRING:
    if (max_length > 255)			// If blob
      break;
    return new Field_string(max_length, maybe_null, name, table,
			    collation.collation);
1216 1217 1218 1219 1220
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
  case MYSQL_TYPE_GEOMETRY:
1221
    break;					// Blob handled outside of case
1222
  }
1223 1224 1225 1226

  /* blob is special as it's generated for both blobs and long strings */
  return new Field_blob(max_length, maybe_null, name, table,
			collation.collation);
1227 1228
}

1229

1230 1231
/* ARGSUSED */
void Item_field::make_field(Send_field *tmp_field)
unknown's avatar
unknown committed
1232
{
1233 1234 1235
  field->make_field(tmp_field);
  if (name)
    tmp_field->col_name=name;			// Use user supplied name
unknown's avatar
unknown committed
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
}

/*
** Set a field:s value from a item
*/


void Item_field::save_org_in_field(Field *to)
{
  if (field->is_null())
  {
    null_value=1;
1248
    set_field_to_null_with_conversions(to, 1);
unknown's avatar
unknown committed
1249 1250 1251 1252 1253 1254 1255 1256 1257
  }
  else
  {
    to->set_notnull();
    field_conv(to,field);
    null_value=0;
  }
}

unknown's avatar
unknown committed
1258
int Item_field::save_in_field(Field *to, bool no_conversions)
unknown's avatar
unknown committed
1259 1260 1261 1262
{
  if (result_field->is_null())
  {
    null_value=1;
1263
    return set_field_to_null_with_conversions(to, no_conversions);
unknown's avatar
unknown committed
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
  }
  else
  {
    to->set_notnull();
    field_conv(to,result_field);
    null_value=0;
  }
  return 0;
}

1274

unknown's avatar
unknown committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
/*
  Store null in field

  SYNOPSIS
    save_in_field()
    field		Field where we want to store NULL

  DESCRIPTION
    This is used on INSERT.
    Allow NULL to be inserted in timestamp and auto_increment values

  RETURN VALUES
    0	 ok
    1	 Field doesn't support NULL values and can't handle 'field = NULL'
*/   

unknown's avatar
unknown committed
1291
int Item_null::save_in_field(Field *field, bool no_conversions)
unknown's avatar
unknown committed
1292
{
1293
  return set_field_to_null_with_conversions(field, no_conversions);
unknown's avatar
unknown committed
1294 1295 1296
}


1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
/*
  Store null in field

  SYNOPSIS
    save_safe_in_field()
    field		Field where we want to store NULL

  RETURN VALUES
    0	 ok
    1	 Field doesn't support NULL values
*/   

unknown's avatar
unknown committed
1309
int Item_null::save_safe_in_field(Field *field)
unknown's avatar
unknown committed
1310 1311 1312 1313 1314
{
  return set_field_to_null(field);
}


unknown's avatar
unknown committed
1315
int Item::save_in_field(Field *field, bool no_conversions)
unknown's avatar
unknown committed
1316
{
1317
  int error;
unknown's avatar
unknown committed
1318 1319 1320 1321 1322
  if (result_type() == STRING_RESULT ||
      result_type() == REAL_RESULT &&
      field->result_type() == STRING_RESULT)
  {
    String *result;
1323
    CHARSET_INFO *cs= collation.collation;
unknown's avatar
unknown committed
1324
    char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
1325
    str_value.set_quick(buff,sizeof(buff),cs);
unknown's avatar
unknown committed
1326 1327
    result=val_str(&str_value);
    if (null_value)
1328
      return set_field_to_null_with_conversions(field, no_conversions);
unknown's avatar
unknown committed
1329
    field->set_notnull();
1330
    error=field->store(result->ptr(),result->length(),cs);
1331
    str_value.set_quick(0, 0, cs);
unknown's avatar
unknown committed
1332 1333 1334 1335 1336 1337 1338
  }
  else if (result_type() == REAL_RESULT)
  {
    double nr=val();
    if (null_value)
      return set_field_to_null(field);
    field->set_notnull();
1339
    error=field->store(nr);
unknown's avatar
unknown committed
1340 1341 1342 1343 1344
  }
  else
  {
    longlong nr=val_int();
    if (null_value)
1345
      return set_field_to_null_with_conversions(field, no_conversions);
unknown's avatar
unknown committed
1346
    field->set_notnull();
1347
    error=field->store(nr);
unknown's avatar
unknown committed
1348
  }
1349
  return (error) ? -1 : 0;
unknown's avatar
unknown committed
1350 1351
}

1352

unknown's avatar
unknown committed
1353
int Item_string::save_in_field(Field *field, bool no_conversions)
unknown's avatar
unknown committed
1354 1355 1356 1357 1358 1359
{
  String *result;
  result=val_str(&str_value);
  if (null_value)
    return set_field_to_null(field);
  field->set_notnull();
1360 1361
  return (field->store(result->ptr(),result->length(),collation.collation)) ? 
	  -1 : 0;
unknown's avatar
unknown committed
1362 1363
}

unknown's avatar
unknown committed
1364
int Item_uint::save_in_field(Field *field, bool no_conversions)
1365
{
1366 1367 1368 1369
  /*
    TODO: To be fixed when wen have a
    field->store(longlong, unsigned_flag) method 
  */
unknown's avatar
unknown committed
1370
  return Item_int::save_in_field(field, no_conversions);
1371 1372
}

unknown's avatar
unknown committed
1373 1374

int Item_int::save_in_field(Field *field, bool no_conversions)
unknown's avatar
unknown committed
1375 1376 1377 1378 1379
{
  longlong nr=val_int();
  if (null_value)
    return set_field_to_null(field);
  field->set_notnull();
1380
  return (field->store(nr)) ? -1 : 0;
unknown's avatar
unknown committed
1381 1382
}

unknown's avatar
unknown committed
1383 1384

int Item_real::save_in_field(Field *field, bool no_conversions)
unknown's avatar
unknown committed
1385 1386 1387 1388 1389
{
  double nr=val();
  if (null_value)
    return set_field_to_null(field);
  field->set_notnull();
1390
  return (field->store(nr)) ? -1 : 0;
unknown's avatar
unknown committed
1391 1392 1393 1394 1395 1396 1397 1398
}

/****************************************************************************
** varbinary item
** In string context this is a binary string
** In number context this is a longlong value.
****************************************************************************/

unknown's avatar
unknown committed
1399
inline uint char_val(char X)
unknown's avatar
unknown committed
1400 1401 1402 1403 1404 1405
{
  return (uint) (X >= '0' && X <= '9' ? X-'0' :
		 X >= 'A' && X <= 'Z' ? X-'A'+10 :
		 X-'a'+10);
}

1406

1407
Item_varbinary::Item_varbinary(const char *str, uint str_length)
unknown's avatar
unknown committed
1408 1409 1410 1411 1412 1413
{
  name=(char*) str-2;				// Lex makes this start with 0x
  max_length=(str_length+1)/2;
  char *ptr=(char*) sql_alloc(max_length+1);
  if (!ptr)
    return;
unknown's avatar
unknown committed
1414
  str_value.set(ptr,max_length,&my_charset_bin);
unknown's avatar
unknown committed
1415 1416 1417 1418 1419 1420 1421 1422 1423
  char *end=ptr+max_length;
  if (max_length*2 != str_length)
    *ptr++=char_val(*str++);			// Not even, assume 0 prefix
  while (ptr != end)
  {
    *ptr++= (char) (char_val(str[0])*16+char_val(str[1]));
    str+=2;
  }
  *ptr=0;					// Keep purify happy
1424
  collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
unknown's avatar
unknown committed
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
}

longlong Item_varbinary::val_int()
{
  char *end=(char*) str_value.ptr()+str_value.length(),
       *ptr=end-min(str_value.length(),sizeof(longlong));

  ulonglong value=0;
  for (; ptr != end ; ptr++)
    value=(value << 8)+ (ulonglong) (uchar) *ptr;
  return (longlong) value;
}


unknown's avatar
unknown committed
1439
int Item_varbinary::save_in_field(Field *field, bool no_conversions)
unknown's avatar
unknown committed
1440
{
1441
  int error;
unknown's avatar
unknown committed
1442 1443 1444
  field->set_notnull();
  if (field->result_type() == STRING_RESULT)
  {
1445
    error=field->store(str_value.ptr(),str_value.length(),collation.collation);
unknown's avatar
unknown committed
1446 1447 1448 1449
  }
  else
  {
    longlong nr=val_int();
1450
    error=field->store(nr);
unknown's avatar
unknown committed
1451
  }
1452
  return (error) ? -1 :  0;
unknown's avatar
unknown committed
1453 1454 1455
}


1456 1457 1458 1459 1460
/*
  Pack data in buffer for sending
*/

bool Item_null::send(Protocol *protocol, String *packet)
unknown's avatar
unknown committed
1461
{
1462
  return protocol->store_null();
unknown's avatar
unknown committed
1463 1464 1465
}

/*
1466
  This is only called from items that is not of type item_field
unknown's avatar
unknown committed
1467 1468
*/

1469
bool Item::send(Protocol *protocol, String *buffer)
unknown's avatar
unknown committed
1470
{
1471 1472 1473 1474 1475 1476
  bool result;
  enum_field_types type;
  LINT_INIT(result);

  switch ((type=field_type())) {
  default:
1477 1478 1479 1480 1481 1482 1483 1484 1485
  case MYSQL_TYPE_NULL:
  case MYSQL_TYPE_DECIMAL:
  case MYSQL_TYPE_ENUM:
  case MYSQL_TYPE_SET:
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
  case MYSQL_TYPE_GEOMETRY:
1486 1487 1488 1489 1490
  case MYSQL_TYPE_STRING:
  case MYSQL_TYPE_VAR_STRING:
  {
    String *res;
    if ((res=val_str(buffer)))
1491
      result= protocol->store(res->ptr(),res->length(),res->charset());
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
    break;
  }
  case MYSQL_TYPE_TINY:
  {
    longlong nr;
    nr= val_int();
    if (!null_value)
      result= protocol->store_tiny(nr);
    break;
  }
  case MYSQL_TYPE_SHORT:
  {
    longlong nr;
    nr= val_int();
    if (!null_value)
      result= protocol->store_short(nr);
    break;
  }
1510
  case MYSQL_TYPE_INT24:
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
  case MYSQL_TYPE_LONG:
  {
    longlong nr;
    nr= val_int();
    if (!null_value)
      result= protocol->store_long(nr);
    break;
  }
  case MYSQL_TYPE_LONGLONG:
  {
    longlong nr;
    nr= val_int();
    if (!null_value)
      result= protocol->store_longlong(nr, unsigned_flag);
    break;
  }
unknown's avatar
unknown committed
1527 1528 1529
  case MYSQL_TYPE_FLOAT:
  {
    float nr;
unknown's avatar
unknown committed
1530
    nr= (float) val();
unknown's avatar
unknown committed
1531 1532 1533 1534
    if (!null_value)
      result= protocol->store(nr, decimals, buffer);
    break;
  }
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
  case MYSQL_TYPE_DOUBLE:
  {
    double nr;
    nr= val();
    if (!null_value)
      result= protocol->store(nr, decimals, buffer);
    break;
  }
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_DATE:
1545
  case MYSQL_TYPE_TIMESTAMP:
1546 1547
  {
    TIME tm;
1548
    get_date(&tm, TIME_FUZZY_DATE);
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    if (!null_value)
    {
      if (type == MYSQL_TYPE_DATE)
	return protocol->store_date(&tm);
      else
	result= protocol->store(&tm);
    }
    break;
  }
  case MYSQL_TYPE_TIME:
  {
    TIME tm;
    get_time(&tm);
    if (!null_value)
      result= protocol->store_time(&tm);
    break;
  }
  }
  if (null_value)
    result= protocol->store_null();
  return result;
unknown's avatar
unknown committed
1570 1571
}

1572 1573

bool Item_field::send(Protocol *protocol, String *buffer)
unknown's avatar
unknown committed
1574
{
1575
  return protocol->store(result_field);
unknown's avatar
unknown committed
1576 1577 1578 1579 1580 1581 1582
}

/*
  This is used for HAVING clause
  Find field in select list having the same name
 */

unknown's avatar
unknown committed
1583
bool Item_ref::fix_fields(THD *thd,TABLE_LIST *tables, Item **reference)
unknown's avatar
unknown committed
1584
{
1585
  uint counter;
unknown's avatar
unknown committed
1586 1587
  if (!ref)
  {
1588
    TABLE_LIST *where= 0, *table_list;
1589
    bool upward_lookup= 0;
unknown's avatar
unknown committed
1590
    SELECT_LEX_UNIT *prev_unit= thd->lex->current_select->master_unit();
1591
    SELECT_LEX *sl= prev_unit->outer_select();
1592 1593 1594 1595 1596
    /*
      Finding only in current select will be performed for selects that have 
      not outer one and for derived tables (which not support using outer 
      fields for now)
    */
unknown's avatar
unknown committed
1597
    if ((ref= find_item_in_list(this, 
unknown's avatar
unknown committed
1598
				*(thd->lex->current_select->get_item_list()),
1599
				&counter,
1600
				((sl && 
unknown's avatar
unknown committed
1601
				  thd->lex->current_select->master_unit()->
1602
				  first_select()->linkage !=
1603 1604 1605
				  DERIVED_TABLE_TYPE) ? 
				  REPORT_EXCEPT_NOT_FOUND :
				  REPORT_ALL_ERRORS))) ==
unknown's avatar
unknown committed
1606
	(Item **)not_found_item)
unknown's avatar
unknown committed
1607
    {
1608
      upward_lookup= 1;
1609
      Field *tmp= (Field*) not_found_field;
unknown's avatar
unknown committed
1610
      /*
unknown's avatar
unknown committed
1611
	We can't find table field in table list of current select,
unknown's avatar
unknown committed
1612
	consequently we have to find it in outer subselect(s).
unknown's avatar
unknown committed
1613 1614 1615
	We can't join lists of outer & current select, because of scope
	of view rules. For example if both tables (outer & current) have
	field 'field' it is not mistake to refer to this field without
unknown's avatar
unknown committed
1616
	mention of table name, but if we join tables in one list it will
1617
	cause error ER_NON_UNIQ_ERROR in find_item_in_list.
unknown's avatar
unknown committed
1618 1619
      */
      SELECT_LEX *last=0;
1620
      for ( ; sl ; sl= (prev_unit= sl->master_unit())->outer_select())
1621
      {
1622
	last= sl;
unknown's avatar
unknown committed
1623
	Item_subselect *prev_subselect_item= prev_unit->item;
1624 1625
	if (sl->resolve_mode == SELECT_LEX::SELECT_MODE &&
	    (ref= find_item_in_list(this, sl->item_list,
1626 1627
				    &counter,
				    REPORT_EXCEPT_NOT_FOUND)) !=
unknown's avatar
unknown committed
1628
	   (Item **)not_found_item)
1629 1630 1631
	{
	  if (*ref && (*ref)->fixed) // Avoid crash in case of error
	  {
unknown's avatar
unknown committed
1632 1633
	    prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
	    prev_subselect_item->const_item_cache&= (*ref)->const_item();
1634
	  }
1635
	  break;
1636
	}
1637
	table_list= sl->get_table_list();
1638
	if (sl->resolve_mode == SELECT_LEX::INSERT_MODE && table_list)
1639 1640 1641 1642
	{
	  // it is primary INSERT st_select_lex => skip first table resolving
	  table_list= table_list->next;
	}
1643
	if ((tmp= find_field_in_tables(thd, this,
1644
				       table_list, &where,
unknown's avatar
unknown committed
1645
				       0)) != not_found_field)
1646
	{
unknown's avatar
unknown committed
1647 1648
	  prev_subselect_item->used_tables_cache|= tmp->table->map;
	  prev_subselect_item->const_item_cache= 0;
unknown's avatar
unknown committed
1649
	  break;
1650 1651 1652
	}

	// Reference is not found => depend from outer (or just error)
unknown's avatar
unknown committed
1653 1654
	prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
	prev_subselect_item->const_item_cache= 0;
1655

1656 1657
	if (sl->master_unit()->first_select()->linkage ==
	    DERIVED_TABLE_TYPE)
1658
	  break; // do not look over derived table
1659
      }
1660

unknown's avatar
unknown committed
1661
      if (!ref)
1662
	return 1;
1663 1664 1665
      else if (!tmp)
	return -1;
      else if (ref == (Item **)not_found_item && tmp == not_found_field)
unknown's avatar
unknown committed
1666
      {
1667
	if (upward_lookup)
unknown's avatar
unknown committed
1668
	{
1669 1670 1671
	  // We can't say exactly what absend (table or field)
	  my_printf_error(ER_BAD_FIELD_ERROR, ER(ER_BAD_FIELD_ERROR), MYF(0),
			  full_name(), thd->where);
unknown's avatar
unknown committed
1672
	}
1673
	else
unknown's avatar
unknown committed
1674
	{
1675 1676
	  // Call to report error
	  find_item_in_list(this,
unknown's avatar
unknown committed
1677
			    *(thd->lex->current_select->get_item_list()),
1678 1679
			    &counter,
			    REPORT_ALL_ERRORS);
unknown's avatar
unknown committed
1680
	}
1681
        ref= 0;
unknown's avatar
unknown committed
1682
	return 1;
unknown's avatar
unknown committed
1683
      }
1684 1685 1686
      else if (tmp != not_found_field)
      {
	ref= 0; // To prevent "delete *ref;" on ~Item_erf() of this item
unknown's avatar
unknown committed
1687 1688
	Item_field* fld;
	if (!((*reference)= fld= new Item_field(tmp)))
1689
	  return 1;
unknown's avatar
unknown committed
1690
	mark_as_dependent(thd, last, thd->lex->current_select, fld);
1691 1692
	return 0;
      }
unknown's avatar
unknown committed
1693 1694
      else
      {
1695 1696 1697 1698 1699 1700
	if (!(*ref)->fixed)
	{
	  my_error(ER_ILLEGAL_REFERENCE, MYF(0), name,
		   "forward reference in item list");
	  return -1;
	}
unknown's avatar
unknown committed
1701
	mark_as_dependent(thd, last, thd->lex->current_select,
unknown's avatar
unknown committed
1702 1703
			  this);
	ref= last->ref_pointer_array + counter;
unknown's avatar
unknown committed
1704 1705
      }
    }
1706
    else if (!ref)
unknown's avatar
unknown committed
1707
      return 1;
1708 1709 1710 1711 1712 1713 1714 1715
    else
    {
      if (!(*ref)->fixed)
      {
	my_error(ER_ILLEGAL_REFERENCE, MYF(0), name,
		 "forward reference in item list");
	return -1;
      }
unknown's avatar
unknown committed
1716
      ref= thd->lex->current_select->ref_pointer_array + counter;
1717
    }
unknown's avatar
unknown committed
1718
  }
1719

1720 1721 1722 1723 1724 1725 1726
  /*
    The following conditional is changed as to correctly identify 
    incorrect references in group functions or forward references 
    with sub-select's / derived tables, while it prevents this 
    check when Item_ref is created in an expression involving 
    summing function, which is to be placed in the user variable.
  */
1727
  if (((*ref)->with_sum_func && name &&
1728
       (depended_from ||
unknown's avatar
unknown committed
1729
	!(thd->lex->current_select->linkage != GLOBAL_OPTIONS_TYPE &&
unknown's avatar
unknown committed
1730
	  thd->lex->current_select->having_fix_field))) ||
1731 1732 1733 1734 1735 1736 1737 1738
      !(*ref)->fixed)
  {
    my_error(ER_ILLEGAL_REFERENCE, MYF(0), name, 
	     ((*ref)->with_sum_func?
	      "reference on group function":
	      "forward reference in item list"));
    return 1;
  }
1739 1740 1741
  max_length= (*ref)->max_length;
  maybe_null= (*ref)->maybe_null;
  decimals=   (*ref)->decimals;
1742
  collation.set((*ref)->collation);
unknown's avatar
unknown committed
1743
  with_sum_func= (*ref)->with_sum_func;
1744
  fixed= 1;
1745

unknown's avatar
unknown committed
1746 1747
  if (ref && (*ref)->check_cols(1))
    return 1;
unknown's avatar
unknown committed
1748 1749 1750
  return 0;
}

1751

unknown's avatar
unknown committed
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
void Item_ref::print(String *str)
{
  if (ref && *ref)
    (*ref)->print(str);
  else
    Item_ident::print(str);
}


void Item_ref_null_helper::print(String *str)
{
1763
  str->append("<ref_null_helper>(", 18);
unknown's avatar
unknown committed
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
  if (ref && *ref)
    (*ref)->print(str);
  else
    str->append('?');
  str->append(')');
}


void Item_null_helper::print(String *str)
{
1774
  str->append("<null_helper>(", 14);
unknown's avatar
unknown committed
1775 1776 1777 1778 1779
  store->print(str);
  str->append(')');
}


unknown's avatar
SCRUM  
unknown committed
1780 1781
bool Item_default_value::eq(const Item *item, bool binary_cmp) const
{
unknown's avatar
SCRUM  
unknown committed
1782
  return item->type() == DEFAULT_VALUE_ITEM && 
unknown's avatar
SCRUM  
unknown committed
1783 1784 1785
    ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
}

1786

unknown's avatar
SCRUM  
unknown committed
1787 1788
bool Item_default_value::fix_fields(THD *thd, struct st_table_list *table_list, Item **items)
{
unknown's avatar
SCRUM  
unknown committed
1789 1790
  if (!arg)
    return false;
unknown's avatar
SCRUM  
unknown committed
1791 1792 1793
  bool res= arg->fix_fields(thd, table_list, items);
  if (res)
    return res;
unknown's avatar
SCRUM  
unknown committed
1794 1795 1796
  /* arg->type() can be only REF_ITEM or FIELD_ITEM for it defined as
   simple_ident in sql_yacc.yy
  */
unknown's avatar
SCRUM  
unknown committed
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
  if (arg->type() == REF_ITEM)
  {
    Item_ref *ref= (Item_ref *)arg;
    if (ref->ref[0]->type() != FIELD_ITEM)
    {
      return 1;
    }
    arg= ref->ref[0];
  }
  Item_field *field_arg= (Item_field *)arg;
  Field *def_field= (Field*) sql_alloc(field_arg->field->size_of());
  if (!def_field)
    return 1;
  memcpy(def_field, field_arg->field, field_arg->field->size_of());
unknown's avatar
unknown committed
1811 1812
  def_field->move_field(def_field->table->default_values -
                        def_field->table->record[0]);
unknown's avatar
SCRUM  
unknown committed
1813 1814 1815 1816
  set_field(def_field);
  return 0;
}

unknown's avatar
SCRUM  
unknown committed
1817 1818
void Item_default_value::print(String *str)
{
unknown's avatar
SCRUM  
unknown committed
1819 1820
  if (!arg)
  {
unknown's avatar
unknown committed
1821
    str->append("default", 7);
unknown's avatar
SCRUM  
unknown committed
1822
    return;
unknown's avatar
SCRUM  
unknown committed
1823
  }
unknown's avatar
unknown committed
1824
  str->append("default(", 8);
unknown's avatar
SCRUM  
unknown committed
1825 1826 1827
  arg->print(str);
  str->append(')');
}
1828

unknown's avatar
unknown committed
1829 1830 1831 1832 1833 1834 1835
bool Item_insert_value::eq(const Item *item, bool binary_cmp) const
{
  return item->type() == INSERT_VALUE_ITEM &&
    ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
}


1836 1837 1838
bool Item_insert_value::fix_fields(THD *thd,
				   struct st_table_list *table_list,
				   Item **items)
unknown's avatar
unknown committed
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
{
  bool res= arg->fix_fields(thd, table_list, items);
  if (res)
    return res;
  /*
    arg->type() can be only REF_ITEM or FIELD_ITEM as arg is
    a simple_ident in sql_yacc.yy
  */
  if (arg->type() == REF_ITEM)
  {
    Item_ref *ref= (Item_ref *)arg;
    if (ref->ref[0]->type() != FIELD_ITEM)
    {
      return 1;
    }
    arg= ref->ref[0];
  }
  Item_field *field_arg= (Item_field *)arg;
  if (field_arg->field->table->insert_values)
  {
    Field *def_field= (Field*) sql_alloc(field_arg->field->size_of());
    if (!def_field)
      return 1;
    memcpy(def_field, field_arg->field, field_arg->field->size_of());
    def_field->move_field(def_field->table->insert_values -
                          def_field->table->record[0]);
    set_field(def_field);
  }
  else
  {
1869
    Field *tmp_field= field_arg->field;
unknown's avatar
unknown committed
1870
    /* charset doesn't matter here, it's to avoid sigsegv only */
1871 1872
    set_field(new Field_null(0, 0, Field::NONE, tmp_field->field_name,
			     tmp_field->table, &my_charset_bin));
unknown's avatar
unknown committed
1873 1874 1875 1876 1877 1878
  }
  return 0;
}

void Item_insert_value::print(String *str)
{
1879
  str->append("values(", 7);
unknown's avatar
unknown committed
1880 1881 1882 1883
  arg->print(str);
  str->append(')');
}

unknown's avatar
unknown committed
1884
/*
1885 1886
  If item is a const function, calculate it and return a const item
  The original item is freed if not returned
unknown's avatar
unknown committed
1887 1888 1889 1890 1891 1892
*/

Item_result item_cmp_type(Item_result a,Item_result b)
{
  if (a == STRING_RESULT && b == STRING_RESULT)
    return STRING_RESULT;
1893
  if (a == INT_RESULT && b == INT_RESULT)
unknown's avatar
unknown committed
1894
    return INT_RESULT;
unknown's avatar
unknown committed
1895 1896
  else if (a == ROW_RESULT || b == ROW_RESULT)
    return ROW_RESULT;
1897
  return REAL_RESULT;
unknown's avatar
unknown committed
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
}


Item *resolve_const_item(Item *item,Item *comp_item)
{
  if (item->basic_const_item())
    return item;				// Can't be better
  Item_result res_type=item_cmp_type(comp_item->result_type(),
				     item->result_type());
  char *name=item->name;			// Alloced by sql_alloc

  if (res_type == STRING_RESULT)
  {
    char buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
1912
    String tmp(buff,sizeof(buff),&my_charset_bin),*result;
unknown's avatar
unknown committed
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
    result=item->val_str(&tmp);
    if (item->null_value)
    {
#ifdef DELETE_ITEMS
      delete item;
#endif
      return new Item_null(name);
    }
    uint length=result->length();
    char *tmp_str=sql_strmake(result->ptr(),length);
#ifdef DELETE_ITEMS
    delete item;
#endif
unknown's avatar
unknown committed
1926
    return new Item_string(name,tmp_str,length,result->charset());
unknown's avatar
unknown committed
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
  }
  if (res_type == INT_RESULT)
  {
    longlong result=item->val_int();
    uint length=item->max_length;
    bool null_value=item->null_value;
#ifdef DELETE_ITEMS
    delete item;
#endif
    return (null_value ? (Item*) new Item_null(name) :
	    (Item*) new Item_int(name,result,length));
  }
  else
  {						// It must REAL_RESULT
    double result=item->val();
    uint length=item->max_length,decimals=item->decimals;
    bool null_value=item->null_value;
#ifdef DELETE_ITEMS
    delete item;
#endif
    return (null_value ? (Item*) new Item_null(name) :
	    (Item*) new Item_real(name,result,decimals,length));
  }
}

/*
  Return true if the value stored in the field is equal to the const item
  We need to use this on the range optimizer because in some cases
  we can't store the value in the field without some precision/character loss.
*/

bool field_is_equal_to_item(Field *field,Item *item)
{

  Item_result res_type=item_cmp_type(field->result_type(),
				     item->result_type());
  if (res_type == STRING_RESULT)
  {
    char item_buff[MAX_FIELD_WIDTH];
    char field_buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
1967 1968
    String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result;
    String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
unknown's avatar
unknown committed
1969 1970 1971 1972
    item_result=item->val_str(&item_tmp);
    if (item->null_value)
      return 1;					// This must be true
    field->val_str(&field_tmp,&field_tmp);
1973
    return !sortcmp(&field_tmp,item_result,&my_charset_bin);
unknown's avatar
unknown committed
1974 1975 1976 1977 1978 1979 1980 1981 1982
  }
  if (res_type == INT_RESULT)
    return 1;					// Both where of type int
  double result=item->val();
  if (item->null_value)
    return 1;
  return result == field->val_real();
}

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
Item_cache* Item_cache::get_cache(Item_result type)
{
  switch (type)
  {
  case INT_RESULT:
    return new Item_cache_int();
  case REAL_RESULT:
    return new Item_cache_real();
  case STRING_RESULT:
    return new Item_cache_str();
unknown's avatar
unknown committed
1993 1994
  case ROW_RESULT:
    return new Item_cache_row();
1995 1996 1997 1998 1999 2000 2001
  default:
    // should never be in real life
    DBUG_ASSERT(0);
    return 0;
  }
}

unknown's avatar
unknown committed
2002 2003 2004

void Item_cache::print(String *str)
{
2005
  str->append("<cache>(", 8);
unknown's avatar
unknown committed
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
  if (example)
    example->print(str);
  else
    Item::print(str);
  str->append(')');
}


void Item_cache_int::store(Item *item)
{
  value= item->val_int_result();
  null_value= item->null_value;
  collation.set(item->collation);
}


void Item_cache_real::store(Item *item)
{
  value= item->val_result();
  null_value= item->null_value;
  collation.set(item->collation);
}


2030 2031
void Item_cache_str::store(Item *item)
{
unknown's avatar
merge  
unknown committed
2032
  value_buff.set(buffer, sizeof(buffer), item->collation.collation);
2033
  value= item->str_result(&value_buff);
2034 2035
  if ((null_value= item->null_value))
    value= 0;
2036
  else if (value != &value_buff)
2037 2038 2039 2040 2041 2042 2043 2044 2045
  {
    /*
      We copy string value to avoid changing value if 'item' is table field
      in queries like following (where t1.c is varchar):
      select a, 
             (select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'),
             (select c from t1 where a=t2.a)
        from t2;
    */
2046 2047
    value_buff.copy(*value);
    value= &value_buff;
2048
  }
unknown's avatar
unknown committed
2049
  collation.set(item->collation);
2050
}
2051 2052


2053 2054
double Item_cache_str::val()
{ 
2055
  int err;
2056
  if (value)
2057
    return my_strntod(value->charset(), (char*) value->ptr(),
2058
		      value->length(), (char**) 0, &err);
2059 2060 2061
  else
    return (double)0;
}
2062 2063


2064 2065
longlong Item_cache_str::val_int()
{
2066
  int err;
2067 2068
  if (value)
    return my_strntoll(value->charset(), value->ptr(),
2069
		       value->length(), 10, (char**) 0, &err);
2070 2071 2072
  else
    return (longlong)0;
}
unknown's avatar
unknown committed
2073

2074

unknown's avatar
unknown committed
2075 2076
bool Item_cache_row::allocate(uint num)
{
unknown's avatar
unknown committed
2077
  item_count= num;
unknown's avatar
unknown committed
2078
  THD *thd= current_thd;
unknown's avatar
unknown committed
2079 2080
  return (!(values= 
	    (Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
unknown's avatar
unknown committed
2081 2082
}

2083

unknown's avatar
unknown committed
2084 2085
bool Item_cache_row::setup(Item * item)
{
unknown's avatar
unknown committed
2086
  example= item;
unknown's avatar
unknown committed
2087 2088
  if (!values && allocate(item->cols()))
    return 1;
unknown's avatar
unknown committed
2089
  for (uint i= 0; i < item_count; i++)
unknown's avatar
unknown committed
2090
  {
unknown's avatar
unknown committed
2091
    Item *el= item->el(i);
unknown's avatar
unknown committed
2092 2093
    Item_cache *tmp;
    if (!(tmp= values[i]= Item_cache::get_cache(el->result_type())))
unknown's avatar
unknown committed
2094
      return 1;
unknown's avatar
unknown committed
2095
    tmp->setup(el);
unknown's avatar
unknown committed
2096 2097 2098 2099
  }
  return 0;
}

2100

unknown's avatar
unknown committed
2101 2102 2103 2104
void Item_cache_row::store(Item * item)
{
  null_value= 0;
  item->bring_value();
unknown's avatar
unknown committed
2105
  for (uint i= 0; i < item_count; i++)
unknown's avatar
unknown committed
2106 2107 2108 2109 2110 2111
  {
    values[i]->store(item->el(i));
    null_value|= values[i]->null_value;
  }
}

2112

unknown's avatar
unknown committed
2113 2114 2115 2116 2117
void Item_cache_row::illegal_method_call(const char *method)
{
  DBUG_ENTER("Item_cache_row::illegal_method_call");
  DBUG_PRINT("error", ("!!! %s method was called for row item", method));
  DBUG_ASSERT(0);
unknown's avatar
unknown committed
2118
  my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
unknown's avatar
unknown committed
2119 2120 2121
  DBUG_VOID_RETURN;
}

2122

unknown's avatar
unknown committed
2123 2124
bool Item_cache_row::check_cols(uint c)
{
unknown's avatar
unknown committed
2125
  if (c != item_count)
unknown's avatar
unknown committed
2126
  {
unknown's avatar
unknown committed
2127
    my_error(ER_OPERAND_COLUMNS, MYF(0), c);
unknown's avatar
unknown committed
2128 2129 2130 2131 2132
    return 1;
  }
  return 0;
}

2133

unknown's avatar
unknown committed
2134 2135
bool Item_cache_row::null_inside()
{
unknown's avatar
unknown committed
2136
  for (uint i= 0; i < item_count; i++)
unknown's avatar
unknown committed
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
  {
    if (values[i]->cols() > 1)
    {
      if (values[i]->null_inside())
	return 1;
    }
    else
    {
      values[i]->val_int();
      if (values[i]->null_value)
	return 1;
    }
  }
  return 0;
}

2153

unknown's avatar
unknown committed
2154 2155
void Item_cache_row::bring_value()
{
unknown's avatar
unknown committed
2156
  for (uint i= 0; i < item_count; i++)
unknown's avatar
unknown committed
2157 2158 2159
    values[i]->bring_value();
  return;
}
unknown's avatar
unknown committed
2160

2161 2162 2163 2164 2165

Item_type_holder::Item_type_holder(THD *thd, Item *item)
  :Item(thd, *item), item_type(item->result_type())
{
  DBUG_ASSERT(item->fixed);
unknown's avatar
unknown committed
2166 2167 2168 2169 2170

  /*
    It is safe assign pointer on field, because it will be used just after
    all JOIN::prepare calls and before any SELECT execution
  */
2171
  if (item->type() == Item::FIELD_ITEM)
unknown's avatar
unknown committed
2172
    field_example= ((Item_field*) item)->field;
2173 2174
  else
    field_example= 0;
2175
  collation.set(item->collation);
2176 2177 2178
}


2179 2180 2181 2182 2183 2184 2185
/*
  STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT

  ROW_RESULT should never appear in Item_type_holder::join_types,
  but it is included in following table just to make table full
  (there DBUG_ASSERT in function to catch ROW_RESULT)
*/
2186 2187 2188 2189 2190 2191
static Item_result type_convertor[4][4]=
{{STRING_RESULT, STRING_RESULT, STRING_RESULT, ROW_RESULT},
 {STRING_RESULT, REAL_RESULT,   REAL_RESULT,   ROW_RESULT},
 {STRING_RESULT, REAL_RESULT,   INT_RESULT,    ROW_RESULT},
 {ROW_RESULT,    ROW_RESULT,    ROW_RESULT,    ROW_RESULT}};

2192
bool Item_type_holder::join_types(THD *thd, Item *item)
2193 2194 2195 2196 2197 2198 2199 2200
{
  bool change_field= 0, skip_store_field= 0;
  Item_result new_type= type_convertor[item_type][item->result_type()];

  // we have both fields
  if (field_example && item->type() == Item::FIELD_ITEM)
  {
    Field *field= ((Item_field *)item)->field;
unknown's avatar
unknown committed
2201
    if (field_example->field_cast_type() != field->field_cast_type())
2202
    {
unknown's avatar
unknown committed
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
      if (!(change_field=
	    field_example->field_cast_compatible(field->field_cast_type())))
      {
	/*
	  if old field can't store value of 'worse' new field we will make
	  decision about result field type based only on Item result type
	*/
	if (!field->field_cast_compatible(field_example->field_cast_type()))
	  skip_store_field= 1;
      }
2213 2214 2215 2216 2217 2218 2219 2220 2221
    }
  }

  // size/type should be changed
  if (change_field ||
      (new_type != item_type) ||
      (max_length < item->max_length) ||
      ((new_type == INT_RESULT) &&
       (decimals < item->decimals)) ||
2222 2223 2224
      (!maybe_null && item->maybe_null) ||
      (item_type == STRING_RESULT && new_type == STRING_RESULT &&
       !my_charset_same(collation.collation, item->collation.collation)))
2225 2226 2227 2228 2229 2230
  {
    // new field has some parameters worse then current
    skip_store_field|= (change_field &&
			(max_length > item->max_length) ||
			((new_type == INT_RESULT) &&
			 (decimals > item->decimals)) ||
2231 2232 2233 2234 2235
			(maybe_null && !item->maybe_null) ||
			(item_type == STRING_RESULT &&
			 new_type == STRING_RESULT &&
			 !my_charset_same(collation.collation,
					  item->collation.collation)));
unknown's avatar
unknown committed
2236 2237 2238 2239
    /*
      It is safe assign pointer on field, because it will be used just after
      all JOIN::prepare calls and before any SELECT execution
    */
2240 2241 2242
    if (skip_store_field || item->type() != Item::FIELD_ITEM)
      field_example= 0;
    else
unknown's avatar
unknown committed
2243 2244
      field_example= ((Item_field*) item)->field;

2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
    const char *old_cs= collation.collation->name,
      *old_derivation= collation.derivation_name();
    if (item_type == STRING_RESULT && collation.aggregate(item->collation))
    {
      my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
	       old_cs, old_derivation,
	       item->collation.collation->name,
	       item->collation.derivation_name(),
	       "UNION");
      return 1;
    }

2257 2258 2259 2260 2261 2262
    max_length= max(max_length, item->max_length);
    decimals= max(decimals, item->decimals);
    maybe_null|= item->maybe_null;
    item_type= new_type;
  }
  DBUG_ASSERT(item_type != ROW_RESULT);
2263
  return 0;
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
}


double Item_type_holder::val()
{
  DBUG_ASSERT(0); // should never be called
  return 0.0;
}


longlong Item_type_holder::val_int()
{
  DBUG_ASSERT(0); // should never be called
  return 0;
}


String *Item_type_holder::val_str(String*)
{
  DBUG_ASSERT(0); // should never be called
  return 0;
}

unknown's avatar
unknown committed
2287 2288 2289 2290 2291 2292 2293
/*****************************************************************************
** Instantiate templates
*****************************************************************************/

#ifdef __GNUC__
template class List<Item>;
template class List_iterator<Item>;
unknown's avatar
unknown committed
2294
template class List_iterator_fast<Item>;
unknown's avatar
unknown committed
2295 2296
template class List<List_item>;
#endif