item.cc 40.7 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
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 26 27 28 29 30 31 32 33 34 35 36
   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"

/*****************************************************************************
** Item functions
*****************************************************************************/

/* Init all special items */

void item_init(void)
{
  item_user_lock_init();
}

37 38
Item::Item():
  fixed(0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
39
{
40
  marker= 0;
41
  maybe_null=null_value=with_sum_func=unsigned_flag=0;
42
  coercibility=COER_IMPLICIT;
43 44 45 46 47
  name= 0;
  decimals= 0; max_length= 0;
  THD *thd= current_thd;
  next= thd->free_list;			// Put in free list
  thd->free_list= this;
48 49 50
  loop_id= 0;
}

51 52 53 54 55 56
/*
  Constructor used by Item_field, Item_ref & agregate (sum) functions.
  Used for duplicating lists in processing queries with temporary
  tables
*/
Item::Item(THD *thd, Item &item):
57 58 59 60 61 62 63 64 65 66
  loop_id(0),
  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),
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
67 68
  fixed(item.fixed),
  coercibility(item.coercibility)
69
{
70 71
  next=thd->free_list;			// Put in free list
  thd->free_list= this;
72 73
}

74 75 76
// Constructor used by Item_field & Item_ref (see Item comment)
Item_ident::Item_ident(THD *thd, Item_ident &item):
  Item(thd, item),
77 78 79 80 81
  db_name(item.db_name),
  table_name(item.table_name),
  field_name(item.field_name),
  depended_from(item.depended_from)
{}
82

83 84 85 86
bool Item::check_cols(uint c)
{
  if (c != 1)
  {
87
    my_error(ER_CARDINALITY_COL, MYF(0), c);
88 89 90 91 92
    return 1;
  }
  return 0;
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
93 94

void Item::set_name(const char *str, uint length, CHARSET_INFO *cs)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
95 96 97
{
  if (!length)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
98 99 100 101 102 103 104 105
    /* Empty string, used by AS or internal function like last_insert_id() */
    name= (char*) str;
    return;
  }
  while (length && !my_isgraph(cs,*str))
  {						// Fix problem with yacc
    length--;
    str++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
106
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
107 108 109 110 111 112 113 114 115
  if (!my_charset_same(cs, system_charset_info))
  {
    uint32 res_length;
    name= sql_strmake_with_convert(str, length, cs,
				   MAX_ALIAS_NAME, system_charset_info,
				   &res_length);
  }
  else
    name=sql_strmake(str, min(length,MAX_ALIAS_NAME));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
116 117
}

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

119
/*
120 121 122
  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
123 124 125
*/

bool Item::eq(const Item *item, bool binary_cmp) const
bk@work.mysql.com's avatar
bk@work.mysql.com committed
126 127
{
  return type() == item->type() && name && item->name &&
128
    !my_strcasecmp(system_charset_info,name,item->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
129 130
}

131 132 133 134 135
bool Item_string::eq(const Item *item, bool binary_cmp) const
{
  if (type() == item->type())
  {
    if (binary_cmp)
136 137
      return !sortcmp(&str_value, &item->str_value, &my_charset_bin);
    return !sortcmp(&str_value, &item->str_value, charset());
138 139 140 141 142
  }
  return 0;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
143 144 145 146 147 148 149 150
/*
  Get the value of the function as a TIME structure.
  As a extra convenience the time structure is reset on error!
 */

bool Item::get_date(TIME *ltime,bool fuzzydate)
{
  char buff[40];
151
  String tmp(buff,sizeof(buff), &my_charset_bin),*res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
152
  if (!(res=val_str(&tmp)) ||
153
      str_to_TIME(res->ptr(),res->length(),ltime,fuzzydate) == TIMESTAMP_NONE)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  {
    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];
169
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
170 171 172 173 174 175 176 177 178
  if (!(res=val_str(&tmp)) ||
      str_to_time(res->ptr(),res->length(),ltime))
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

179
CHARSET_INFO * Item::default_charset() const
180
{
181
  return current_thd->variables.collation_connection;
182 183
}

184 185 186 187 188 189 190 191
bool Item::set_charset(CHARSET_INFO *cs1, enum coercion co1,
		       CHARSET_INFO *cs2, enum coercion co2)
{
  if (cs1 == &my_charset_bin || cs2 == &my_charset_bin)
  {
    set_charset(&my_charset_bin, COER_NOCOLL);
    return 0;
  }
192

193
  if (!my_charset_same(cs1,cs2))
194 195
    return 1;

196 197 198 199 200 201 202 203 204 205 206
  if (co1 < co2)
  {
    set_charset(cs1, co1);
  }
  else if (co2 < co1)
  {
    set_charset(cs2, co2);
  }
  else  // co2 == co1
  {
    if (cs1 != cs2)
207
    {
208 209 210 211 212 213 214 215 216 217 218
      if (co1 == COER_EXPLICIT)
      {
        return 1;
      }
      else
      {
        CHARSET_INFO *bin= get_charset_by_csname(cs1->csname, MY_CS_BINSORT,MYF(0));
        if (!bin)
	  return 1;
        set_charset(bin, COER_NOCOLL);
      }
219
    }
220 221 222 223 224 225
    else
      set_charset(cs2, co2);
  }
  return 0;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
226 227 228
Item_field::Item_field(Field *f) :Item_ident(NullS,f->table_name,f->field_name)
{
  set_field(f);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
229
  coercibility= COER_IMPLICIT;
230
  fixed= 1; // This item is not needed in fix_fields
bk@work.mysql.com's avatar
bk@work.mysql.com committed
231 232
}

233 234 235
// Constructor need to process subselect with temporary tables (see Item)
Item_field::Item_field(THD *thd, Item_field &item):
  Item_ident(thd, item),
236 237
  field(item.field),
  result_field(item.result_field)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
238
{ coercibility= COER_IMPLICIT; }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
239 240 241 242 243 244 245 246 247

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;
248
  db_name=field_par->table->table_cache_key;
249
  unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
250
  set_charset(field_par->charset(), COER_IMPLICIT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
251 252 253 254 255 256 257
}

const char *Item_ident::full_name() const
{
  char *tmp;
  if (!table_name)
    return field_name ? field_name : name ? name : "tmp_field";
258
  if (db_name && db_name[0])
bk@work.mysql.com's avatar
bk@work.mysql.com committed
259
  {
260 261
    tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
			  (uint) strlen(field_name)+3);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
262 263 264 265
    strxmov(tmp,db_name,".",table_name,".",field_name,NullS);
  }
  else
  {
266 267
    tmp=(char*) sql_alloc((uint) strlen(table_name)+
			  (uint) strlen(field_name)+2);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
268 269 270 271 272 273 274 275 276 277
    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;
278
  str->set_charset(str_value.charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  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;
301
  str->set_charset(str_value.charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
302 303 304 305 306 307 308 309 310 311 312 313 314
  return result_field->val_str(str,&str_value);
}

bool Item_field::get_date(TIME *ltime,bool fuzzydate)
{
  if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

315 316 317 318 319 320 321 322 323 324 325
bool Item_field::get_date_result(TIME *ltime,bool fuzzydate)
{
  if ((null_value=result_field->is_null()) ||
      result_field->get_date(ltime,fuzzydate))
  {
    bzero((char*) ltime,sizeof(*ltime));
    return 1;
  }
  return 0;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
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();
}

350

351
bool Item_field::eq(const Item *item, bool binary_cmp) const
bk@work.mysql.com's avatar
bk@work.mysql.com committed
352
{
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  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))))));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
378 379 380 381 382 383
}

table_map Item_field::used_tables() const
{
  if (field->table->const_table)
    return 0;					// const item
384
  return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
385 386
}

387
Item *Item_field::get_tmp_table_item(THD *thd)
388
{
389
  Item_field *new_item= new Item_field(thd, *this);
390 391 392 393
  if (new_item)
    new_item->field= new_item->result_field;
  return new_item;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
394 395 396

String *Item_int::val_str(String *str)
{
397
  str->set(value, default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
398 399 400 401 402 403 404
  return str;
}

void Item_int::print(String *str)
{
  if (!name)
  {
405
    str_value.set(value, default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
406 407 408 409 410
    name=str_value.c_ptr();
  }
  str->append(name);
}

411 412
String *Item_uint::val_str(String *str)
{
413
  str->set((ulonglong) value, default_charset());
414 415 416 417 418 419 420
  return str;
}

void Item_uint::print(String *str)
{
  if (!name)
  {
421
    str_value.set((ulonglong) value, default_charset());
422 423 424 425 426
    name=str_value.c_ptr();
  }
  str->append(name);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
427 428 429

String *Item_real::val_str(String *str)
{
430
  str->set(value,decimals,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
431 432 433 434 435 436 437 438 439 440
  return str;
}

void Item_string::print(String *str)
{
  str->append('\'');
  str->append(full_name());
  str->append('\'');
}

441 442
bool Item_null::eq(const Item *item, bool binary_cmp) const
{ return item->type() == type(); }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
443 444 445 446 447 448 449
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;}


450 451 452 453 454 455 456 457 458 459 460 461
/* Item_param related */
void Item_param::set_null()
{ 
  maybe_null=null_value=1;    
}

void Item_param::set_int(longlong i)
{  
  int_value=(longlong)i; 
  item_type = INT_ITEM;
}

462
void Item_param::set_double(double value)
463 464 465 466 467 468
{  
  real_value=value;
  item_type = REAL_ITEM;
}


venu@myvenu.com's avatar
venu@myvenu.com committed
469
void Item_param::set_value(const char *str, uint length)
470
{  
471
  str_value.set(str,length,default_charset());
472 473 474
  item_type = STRING_ITEM;
}

475

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
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;
}


venu@myvenu.com's avatar
venu@myvenu.com committed
495 496 497 498
void Item_param::set_longdata(const char *str, ulong length)
{  
  str_value.append(str,length);
  long_data_supplied= 1;
499 500 501
}


venu@myvenu.com's avatar
venu@myvenu.com committed
502
int Item_param::save_in_field(Field *field, bool no_conversions)
503 504
{
  if (null_value)
505
    return (int) set_field_to_null(field);   
506 507 508 509 510
    
  field->set_notnull();
  if (item_result_type == INT_RESULT)
  {
    longlong nr=val_int();
511
    return (field->store(nr)) ? -1 : 0;
512 513 514 515
  }
  if (item_result_type == REAL_RESULT)
  {
    double nr=val();    
516
    return (field->store(nr)) ? -1 : 0; 
517 518 519 520 521
  }  
  if (item_is_time)
  {
    field->store_time(&ltime, ltime.time_type);
    return 0;
522
  }
523 524
  String *result=val_str(&str_value);
  return (field->store(result->ptr(),result->length(),field->charset())) ? -1 : 0;
525 526
}

527 528 529 530 531
bool Item_param::get_time(TIME *res)
{
  *res=ltime;
  return 0;
}
532

533 534
double Item_param::val() 
{
535
  int err;
536
  switch (item_result_type) {
537
  case STRING_RESULT:
538
    return (double) my_strntod(str_value.charset(), (char*) str_value.ptr(),
539
			       str_value.length(), (char**) 0, &err); 
540 541 542 543 544 545 546
  case INT_RESULT:
    return (double)int_value;
  default:
    return real_value;
  }
} 

547

548 549
longlong Item_param::val_int() 
{ 
550
 int err;
551
 switch (item_result_type) {
552
  case STRING_RESULT:
553 554 555
    return my_strntoll(str_value.charset(),
		       str_value.ptr(),str_value.length(),10,
		       (char**) 0,&err);
556 557 558 559 560 561 562
  case REAL_RESULT:
    return (longlong) (real_value+(real_value > 0 ? 0.5 : -0.5));
  default:
    return int_value;
  }
}

563

564 565
String *Item_param::val_str(String* str) 
{ 
566
  switch (item_result_type) {
567
  case INT_RESULT:
568
    str->set(int_value, default_charset());
569 570
    return str;
  case REAL_RESULT:
571
    str->set(real_value, 2, default_charset());
572 573 574 575 576
    return str;
  default:
    return (String*) &str_value;
  }
}
577 578 579 580 581 582 583 584 585 586 587

/*
  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:
588
    return val_str(str);
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    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
    {
      char buff[25];
      
      switch (ltime.time_type)  {
        case TIMESTAMP_NONE:
          break;
        case TIMESTAMP_DATE:
          sprintf(buff, "%04d-%02d-%02d", 
                        ltime.year,ltime.month,ltime.day);
          str->append(buff, 10);
          break;
        case TIMESTAMP_FULL:
          sprintf(buff, "%04d-%02d-%02d %02d:%02d:%02d",
 	                ltime.year,ltime.month,ltime.day,
632
	                ltime.hour,ltime.minute,ltime.second);
633 634 635 636 637
          str->append(buff, 19);
          break;
        case TIMESTAMP_TIME:
        {
          sprintf(buff, "%02d:%02d:%02d",
638
	  	            ltime.hour,ltime.minute,ltime.second);
639 640 641 642 643 644 645 646 647
          str->append(buff, 8);
          break;
        }
      }
    }
    str->append("'");
  }
  return str;
}
648 649
/* End of Item_param related */

650

bk@work.mysql.com's avatar
bk@work.mysql.com committed
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
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;
}

/*
668
  Functions to convert item to field (for send_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
669 670 671 672
*/

/* ARGSUSED */
bool Item::fix_fields(THD *thd,
673 674
		      struct st_table_list *list,
		      Item ** ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
675
{
676
  fixed= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
677 678 679
  return 0;
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
680 681 682 683 684 685
bool Item_asterisk_remover::fix_fields(THD *thd,
				       struct st_table_list *list,
				       Item ** ref)
{
  DBUG_ENTER("Item_asterisk_remover::fix_fields");
  
686
  bool res= 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
687 688 689 690
  if (item)
    if (item->type() == Item::FIELD_ITEM &&
	((Item_field*) item)->field_name[0] == '*')
    {
691
      Item_field *fitem=  (Item_field*) item;
692 693
      if (list)
	if (!list->next || fitem->db_name || fitem->table_name)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
694
	{
695 696 697 698
	  TABLE_LIST *table= find_table_in_list(list,
						fitem->db_name,
						fitem->table_name);
	  if (table)
699
	  {
700 701 702 703
	    TABLE * tb= table->table;
	    if (find_table_in_list(table->next, fitem->db_name,
				   fitem->table_name) != 0 ||
		tb->fields == 1)
704
	    {
705 706 707 708 709 710 711 712
	      if ((item= new Item_field(tb->field[0])))
	      {
		res= 0;
		tb->field[0]->query_id= thd->query_id;
		tb->used_keys&= tb->field[0]->part_of_key;
		tb->used_fields= tb->fields;
	      }
	      else
713
		thd->fatal_error(); // can't create Item => out of memory
714 715
	    }
	    else
716
	      my_error(ER_CARDINALITY_COL, MYF(0), 1);
717 718
	  }
	  else
719
	    my_error(ER_BAD_TABLE_ERROR, MYF(0), fitem->table_name);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
720
	}
721
	else
722
	  my_error(ER_CARDINALITY_COL, MYF(0), 1);
723
      else
724
	my_error(ER_NO_TABLES_USED, MYF(0));
725
    }   
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
726 727 728
    else
      res= item->fix_fields(thd, list, &item);
  else
729
    thd->fatal_error(); // no item given => out of memory
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
730 731 732
  DBUG_RETURN(res);
}

733 734 735 736
bool Item_ref_on_list_position::fix_fields(THD *thd,
					   struct st_table_list *tables,
					   Item ** reference)
{
737
  if (select_lex->item_list.elements <= pos)
738
  {
739
    ref= 0;
740 741 742
    my_error(ER_CARDINALITY_COL, MYF(0), pos);
    return 1;
  }
743 744
  ref= select_lex->ref_pointer_array + pos;
  return Item_ref_null_helper::fix_fields(thd, tables, reference);
745 746
}

747 748 749
double Item_ref_null_helper::val()
{
  double tmp= (*ref)->val_result();
750
  owner->was_null|= null_value= (*ref)->null_value;
751 752 753 754 755
  return tmp;
}
longlong Item_ref_null_helper::val_int()
{
  longlong tmp= (*ref)->val_int_result();
756
  owner->was_null|= null_value= (*ref)->null_value;
757 758 759 760 761
  return tmp;
}
String* Item_ref_null_helper::val_str(String* s)
{
  String* tmp= (*ref)->str_result(s);
762
  owner->was_null|= null_value= (*ref)->null_value;
763 764 765 766 767 768
  return tmp;
}
bool Item_ref_null_helper::get_date(TIME *ltime, bool fuzzydate)
{  
  return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate));
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
769

770
bool Item_field::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
771
{
772
  if (!field)					// If field is not checked
bk@work.mysql.com's avatar
bk@work.mysql.com committed
773
  {
774 775 776 777 778
    TABLE_LIST *where= 0;
    Field *tmp= (Field *)not_found_field;
    if (outer_resolving || 
	(tmp= find_field_in_tables(thd, this, tables, &where, 0)) ==
	not_found_field)
779 780 781 782 783 784 785 786 787 788
    {
      /*
	We can't find table field in table list of current select, 
	consequently we have to find it in outer subselect(s).
	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 
	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.
      */
789
      SELECT_LEX *last= 0;
hf@bisonxp.(none)'s avatar
hf@bisonxp.(none) committed
790 791 792
#ifdef EMBEDDED_LIBRARY
      thd->net.last_errno= 0;
#endif
793
      Item **refer= (Item **)not_found_item;
794
      uint counter;
795
      // Prevent using outer fields in subselects, that is not supported now
796
      SELECT_LEX *cursel=(SELECT_LEX *) thd->lex.current_select;
797 798
      if (outer_resolving ||
	  cursel->master_unit()->first_select()->linkage != DERIVED_TABLE_TYPE)
799
	for (SELECT_LEX *sl=(outer_resolving?cursel:cursel->outer_select());
800 801
	     sl;
	     sl= sl->outer_select())
802
	{
803
	  if ((tmp= find_field_in_tables(thd, this,
804
					 (last= sl)->get_table_list(), &where,
805 806
					 0)) != not_found_field)
	    break;
807
	  if ((refer= find_item_in_list(this, sl->item_list, &counter, 
808
					 REPORT_EXCEPT_NOT_FOUND)) != 
809
	       (Item **) not_found_item)
810
	    break;
811 812
	  if (sl->master_unit()->first_select()->linkage ==
	      DERIVED_TABLE_TYPE)
813
	    break; // do not look over derived table
814
	}
815
      if (!tmp)
816
	return -1;
817 818 819
      else if (!refer)
	return 1;
      else if (tmp == not_found_field && refer == (Item **)not_found_item)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
820
      {
821
	// call to return error code
822
	find_field_in_tables(thd, this, tables, &where, 1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
823 824
	return -1;
      }
825 826
      else if (refer != (Item **)not_found_item)
      {
827 828 829 830 831 832 833
	if (!(*refer)->fixed)
	{
	  my_error(ER_ILLEGAL_REFERENCE, MYF(0), name,
		   "forward reference in item list");
	  return -1;
	}

834
	Item_ref *r;
835
	*ref= r= new Item_ref(last->ref_pointer_array + counter
836
			      , (char *)table_name,
837 838 839
			   (char *)field_name);
	if (!r)
	  return 1;
840
	if (r->fix_fields(thd, tables, ref) || r->check_cols(1))
841
	  return 1;
842
	// store pointer on SELECT_LEX from which item is dependent
843
	r->depended_from= last;
844
	cursel->mark_as_dependent(last);
845 846
	return 0;
      }
847
      else
848
      {
849
	// store pointer on SELECT_LEX from wich item is dependent
850
	depended_from= last;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
851 852 853 854
	/*
	  Mark all selects from resolved to 1 before select where was 
	  found table as depended (of select where was found table)
	*/
855
	thd->lex.current_select->mark_as_dependent(last);
856 857 858 859 860 861 862 863 864
	if (depended_from->having_fix_field)
	{
	  Item_ref *rf;
	  *ref= rf= new Item_ref((where->db[0]?where->db:0), 
				 (char *)where->alias,
				 (char *)field_name);
	  if (!rf)
	    return 1;
	  (rf)->outer_resolving= outer_resolving;
865
	  return rf->fix_fields(thd, tables, ref) ||  rf->check_cols(1);
866
	}
867
      }
868
    }
869 870 871
    else if (!tmp)
      return -1;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
872 873
    set_field(tmp);
  }
874 875 876 877 878 879 880 881
  else if (thd && thd->set_query_id && field->query_id != thd->query_id)
  {
    /* We only come here in unions */
    TABLE *table=field->table;
    field->query_id=thd->query_id;
    table->used_fields++;
    table->used_keys&=field->part_of_key;
  }
882
  fixed= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
883 884 885 886 887 888
  return 0;
}


void Item::init_make_field(Send_field *tmp_field,
			   enum enum_field_types field_type)
889
{  
890 891 892 893 894 895 896
  char *empty_name= (char*) "";
  tmp_field->db_name=	 	empty_name;
  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;
  tmp_field->charsetnr= 	charset()->number;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
897 898 899 900
  tmp_field->flags=maybe_null ? 0 : NOT_NULL_FLAG;
  tmp_field->type=field_type;
  tmp_field->length=max_length;
  tmp_field->decimals=decimals;
901 902
  if (unsigned_flag)
    tmp_field->flags |= UNSIGNED_FLAG;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
903 904
}

905
void Item::make_field(Send_field *tmp_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
906
{
907
  init_make_field(tmp_field, field_type());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
908 909
}

910
enum_field_types Item::field_type() const
bk@work.mysql.com's avatar
bk@work.mysql.com committed
911
{
912 913 914
  return ((result_type() == STRING_RESULT) ? FIELD_TYPE_VAR_STRING :
	  (result_type() == INT_RESULT) ? FIELD_TYPE_LONGLONG :
	  FIELD_TYPE_DOUBLE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
915 916
}

917 918
/* ARGSUSED */
void Item_field::make_field(Send_field *tmp_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
919
{
920 921 922
  field->make_field(tmp_field);
  if (name)
    tmp_field->col_name=name;			// Use user supplied name
bk@work.mysql.com's avatar
bk@work.mysql.com committed
923 924 925 926 927 928 929 930 931 932 933 934
}

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


void Item_field::save_org_in_field(Field *to)
{
  if (field->is_null())
  {
    null_value=1;
935
    set_field_to_null_with_conversions(to, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
936 937 938 939 940 941 942 943 944
  }
  else
  {
    to->set_notnull();
    field_conv(to,field);
    null_value=0;
  }
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
945
int Item_field::save_in_field(Field *to, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
946 947 948 949
{
  if (result_field->is_null())
  {
    null_value=1;
950
    return set_field_to_null_with_conversions(to, no_conversions);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
951 952 953 954 955 956 957 958 959 960
  }
  else
  {
    to->set_notnull();
    field_conv(to,result_field);
    null_value=0;
  }
  return 0;
}

961

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
/*
  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'
*/   

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
978
int Item_null::save_in_field(Field *field, bool no_conversions)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
979
{
980
  return set_field_to_null_with_conversions(field, no_conversions);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
981 982 983
}


984 985 986 987 988 989 990 991 992 993 994 995
/*
  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
*/   

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
996
int Item_null::save_safe_in_field(Field *field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
997 998 999 1000 1001
{
  return set_field_to_null(field);
}


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1002
int Item::save_in_field(Field *field, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1003
{
1004
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1005 1006 1007 1008 1009
  if (result_type() == STRING_RESULT ||
      result_type() == REAL_RESULT &&
      field->result_type() == STRING_RESULT)
  {
    String *result;
1010
    CHARSET_INFO *cs=charset();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1011
    char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
1012
    str_value.set_quick(buff,sizeof(buff),cs);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1013 1014
    result=val_str(&str_value);
    if (null_value)
1015
      return set_field_to_null_with_conversions(field, no_conversions);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1016
    field->set_notnull();
1017
    error=field->store(result->ptr(),result->length(),cs);
1018
    str_value.set_quick(0, 0, cs);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1019 1020 1021 1022 1023 1024 1025
  }
  else if (result_type() == REAL_RESULT)
  {
    double nr=val();
    if (null_value)
      return set_field_to_null(field);
    field->set_notnull();
1026
    error=field->store(nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1027 1028 1029 1030 1031
  }
  else
  {
    longlong nr=val_int();
    if (null_value)
1032
      return set_field_to_null_with_conversions(field, no_conversions);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1033
    field->set_notnull();
1034
    error=field->store(nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1035
  }
1036
  return (error) ? -1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1037 1038
}

1039

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1040
int Item_string::save_in_field(Field *field, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1041 1042 1043 1044 1045 1046
{
  String *result;
  result=val_str(&str_value);
  if (null_value)
    return set_field_to_null(field);
  field->set_notnull();
1047
  return (field->store(result->ptr(),result->length(),charset())) ? -1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1048 1049
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1050 1051

int Item_int::save_in_field(Field *field, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1052 1053 1054 1055 1056
{
  longlong nr=val_int();
  if (null_value)
    return set_field_to_null(field);
  field->set_notnull();
1057
  return (field->store(nr)) ? -1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1058 1059
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1060 1061

int Item_real::save_in_field(Field *field, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1062 1063 1064 1065 1066
{
  double nr=val();
  if (null_value)
    return set_field_to_null(field);
  field->set_notnull();
1067
  return (field->store(nr)) ? -1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1068 1069 1070 1071 1072 1073 1074 1075
}

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

1076
inline uint char_val(char X)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1077 1078 1079 1080 1081 1082
{
  return (uint) (X >= '0' && X <= '9' ? X-'0' :
		 X >= 'A' && X <= 'Z' ? X-'A'+10 :
		 X-'a'+10);
}

1083

1084
Item_varbinary::Item_varbinary(const char *str, uint str_length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1085 1086 1087 1088 1089 1090
{
  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;
1091
  str_value.set(ptr,max_length,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1092 1093 1094 1095 1096 1097 1098 1099 1100
  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
1101
  coercibility= COER_COERCIBLE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
}

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


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1116
int Item_varbinary::save_in_field(Field *field, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1117
{
1118
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1119 1120 1121
  field->set_notnull();
  if (field->result_type() == STRING_RESULT)
  {
1122
    error=field->store(str_value.ptr(),str_value.length(),charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1123 1124 1125 1126
  }
  else
  {
    longlong nr=val_int();
1127
    error=field->store(nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1128
  }
1129
  return (error) ? -1 :  0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1130 1131 1132
}


1133 1134 1135 1136 1137
/*
  Pack data in buffer for sending
*/

bool Item_null::send(Protocol *protocol, String *packet)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1138
{
1139
  return protocol->store_null();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1140 1141 1142
}

/*
1143
  This is only called from items that is not of type item_field
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1144 1145
*/

1146
bool Item::send(Protocol *protocol, String *buffer)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1147
{
1148 1149 1150 1151 1152 1153
  bool result;
  enum_field_types type;
  LINT_INIT(result);

  switch ((type=field_type())) {
  default:
1154 1155 1156 1157 1158 1159 1160 1161 1162
  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:
1163 1164 1165 1166 1167
  case MYSQL_TYPE_STRING:
  case MYSQL_TYPE_VAR_STRING:
  {
    String *res;
    if ((res=val_str(buffer)))
1168
      result= protocol->store(res->ptr(),res->length(),res->charset());
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    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;
  }
1187
  case MYSQL_TYPE_INT24:
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  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;
  }
  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:
1214
  case MYSQL_TYPE_TIMESTAMP:
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  {
    TIME tm;
    get_date(&tm, 1);
    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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1239 1240
}

1241 1242

bool Item_field::send(Protocol *protocol, String *buffer)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1243
{
1244
  return protocol->store(result_field);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1245 1246 1247 1248 1249 1250 1251
}

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

1252
bool Item_ref::fix_fields(THD *thd,TABLE_LIST *tables, Item **reference)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1253
{
1254
  uint counter;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1255 1256
  if (!ref)
  {
1257 1258 1259 1260
    TABLE_LIST *where= 0;
    SELECT_LEX *sl= (outer_resolving?
		     thd->lex.current_select->select_lex():
		     thd->lex.current_select->outer_select());
1261 1262 1263 1264 1265
    /*
      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)
    */
1266 1267
    if (outer_resolving ||
	(ref= find_item_in_list(this, 
1268
				*(thd->lex.current_select->get_item_list()),
1269
				&counter,
1270
				((sl && 
1271 1272
				  thd->lex.current_select->master_unit()->
				  first_select()->linkage !=
1273 1274 1275
				  DERIVED_TABLE_TYPE) ? 
				  REPORT_EXCEPT_NOT_FOUND :
				  REPORT_ALL_ERRORS))) ==
1276
	(Item **)not_found_item)
1277
    {
1278
      Field *tmp= (Field*) not_found_field;
1279
      /*
1280
	We can't find table field in table list of current select,
1281
	consequently we have to find it in outer subselect(s).
1282 1283 1284
	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
1285
	mention of table name, but if we join tables in one list it will
1286
	cause error ER_NON_UNIQ_ERROR in find_item_in_list.
1287 1288
      */
      SELECT_LEX *last=0;
1289
      for ( ; sl ; sl= sl->outer_select())
1290 1291
      {
	if ((ref= find_item_in_list(this, (last= sl)->item_list,
1292 1293
				    &counter,
				    REPORT_EXCEPT_NOT_FOUND)) !=
1294
	   (Item **)not_found_item)
1295
	  break;
1296
	if ((tmp= find_field_in_tables(thd, this,
1297
				       sl->get_table_list(), &where,
1298 1299
				       0)) != not_found_field)
	  break;
1300 1301
	if (sl->master_unit()->first_select()->linkage ==
	    DERIVED_TABLE_TYPE)
1302
	  break; // do not look over derived table
1303
      }
1304

1305
      if (!ref)
1306
	return 1;
1307 1308 1309
      else if (!tmp)
	return -1;
      else if (ref == (Item **)not_found_item && tmp == not_found_field)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1310 1311
      {
	// Call to report error
1312 1313
	find_item_in_list(this,
			  *(thd->lex.current_select->get_item_list()),
1314
			  &counter,
1315 1316
			  REPORT_ALL_ERRORS);
        ref= 0;
1317
	return 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1318
      }
1319 1320 1321 1322 1323 1324
      else if (tmp != not_found_field)
      {
	ref= 0; // To prevent "delete *ref;" on ~Item_erf() of this item
	Item_field* f;
	if (!((*reference)= f= new Item_field(tmp)))
	  return 1;
1325
	// store pointer on SELECT_LEX from wich item is dependent
1326 1327 1328 1329
	f->depended_from= last;
	thd->lex.current_select->mark_as_dependent(last);
	return 0;
      }
1330 1331
      else
      {
1332 1333 1334 1335 1336 1337
	if (!(*ref)->fixed)
	{
	  my_error(ER_ILLEGAL_REFERENCE, MYF(0), name,
		   "forward reference in item list");
	  return -1;
	}
1338 1339 1340 1341
        /*
	  depended_from: pointer on SELECT_LEX from wich item is dependent
	*/
	ref= (depended_from= last)->ref_pointer_array + counter;
1342
	thd->lex.current_select->mark_as_dependent(last);
1343 1344
      }
    }
1345
    else if (!ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1346
      return 1;
1347 1348 1349 1350 1351 1352 1353 1354
    else
    {
      if (!(*ref)->fixed)
      {
	my_error(ER_ILLEGAL_REFERENCE, MYF(0), name,
		 "forward reference in item list");
	return -1;
      }
1355
      ref= thd->lex.current_select->ref_pointer_array + counter;
1356
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1357
  }
1358

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
/*
 * 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.
 *
 */
 
  if (((*ref)->with_sum_func && name &&
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
       (depended_from || 
	!(thd->lex.current_select->linkage != GLOBAL_OPTIONS_TYPE &&
	  thd->lex.current_select->select_lex()->having_fix_field))) ||
      !(*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;
  }
1380 1381 1382
  max_length= (*ref)->max_length;
  maybe_null= (*ref)->maybe_null;
  decimals=   (*ref)->decimals;
1383
  set_charset((*ref)->charset());
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1384
  with_sum_func= (*ref)->with_sum_func;
1385
  fixed= 1;
1386

1387 1388
  if (ref && (*ref)->check_cols(1))
    return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389 1390 1391
  return 0;
}

1392

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1393 1394
bool Item_default_value::eq(const Item *item, bool binary_cmp) const
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1395
  return item->type() == DEFAULT_VALUE_ITEM && 
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1396 1397 1398
    ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
}

1399

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1400 1401
bool Item_default_value::fix_fields(THD *thd, struct st_table_list *table_list, Item **items)
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1402 1403
  if (!arg)
    return false;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1404 1405 1406
  bool res= arg->fix_fields(thd, table_list, items);
  if (res)
    return res;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1407 1408 1409
  /* arg->type() can be only REF_ITEM or FIELD_ITEM for it defined as
   simple_ident in sql_yacc.yy
  */
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  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());
1424 1425
  def_field->move_field(def_field->table->default_values -
                        def_field->table->record[0]);
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1426 1427 1428 1429
  set_field(def_field);
  return 0;
}

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1430 1431
void Item_default_value::print(String *str)
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1432 1433 1434
  if (!arg)
  {
    str->append("DEFAULT");
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1435
    return;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1436 1437
  }
  str->append("DEFAULT(");
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1438 1439 1440
  arg->print(str);
  str->append(')');
}
1441

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
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);
}


bool Item_insert_value::fix_fields(THD *thd, struct st_table_list *table_list, Item **items)
{
  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
  {
    Field *field=field_arg->field;
    /* charset doesn't matter here, it's to avoid sigsegv only */
    set_field(new Field_null(0,0,Field::NONE,field->field_name,field->table,
1483
          &my_charset_bin));
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
  }
  return 0;
}

void Item_insert_value::print(String *str)
{
  str->append("VALUE(");
  arg->print(str);
  str->append(')');
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1495
/*
1496 1497
  If item is a const function, calculate it and return a const item
  The original item is freed if not returned
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1498 1499 1500 1501 1502 1503 1504 1505
*/

Item_result item_cmp_type(Item_result a,Item_result b)
{
  if (a == STRING_RESULT && b == STRING_RESULT)
    return STRING_RESULT;
  else if (a == INT_RESULT && b == INT_RESULT)
    return INT_RESULT;
1506 1507
  else if (a == ROW_RESULT || b == ROW_RESULT)
    return ROW_RESULT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
  else
    return REAL_RESULT;
}


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];
1524
    String tmp(buff,sizeof(buff),&my_charset_bin),*result;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    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
1538
    return new Item_string(name,tmp_str,length,result->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
  }
  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];
1579 1580
    String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result;
    String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1581 1582 1583 1584
    item_result=item->val_str(&item_tmp);
    if (item->null_value)
      return 1;					// This must be true
    field->val_str(&field_tmp,&field_tmp);
1585
    return !sortcmp(&field_tmp,item_result,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1586 1587 1588 1589 1590 1591 1592 1593 1594
  }
  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();
}

1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
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();
1605 1606
  case ROW_RESULT:
    return new Item_cache_row();
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
  default:
    // should never be in real life
    DBUG_ASSERT(0);
    return 0;
  }
}

void Item_cache_str::store(Item *item)
{
  str_value.set(buffer, sizeof(buffer), item->charset());
  value= item->str_result(&str_value);
  if ((null_value= item->null_value))
    value= 0;
  else if (value != &str_value)
  {
    /*
      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;
    */
    str_value.copy(*value);
    value= &str_value;
  }

}
double Item_cache_str::val()
{ 
1637
  int err;
1638
  if (value)
1639
    return my_strntod(value->charset(), (char*) value->ptr(),
1640
		      value->length(), (char**) 0, &err);
1641 1642 1643 1644 1645
  else
    return (double)0;
}
longlong Item_cache_str::val_int()
{
1646
  int err;
1647 1648
  if (value)
    return my_strntoll(value->charset(), value->ptr(),
1649
		       value->length(), 10, (char**) 0, &err);
1650 1651 1652
  else
    return (longlong)0;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1653

1654 1655
bool Item_cache_row::allocate(uint num)
{
1656
  item_count= num;
1657
  THD *thd= current_thd;
1658 1659
  return (!(values= 
	    (Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
1660 1661 1662 1663 1664 1665
}

bool Item_cache_row::setup(Item * item)
{
  if (!values && allocate(item->cols()))
    return 1;
1666
  for (uint i= 0; i < item_count; i++)
1667
  {
1668
    Item *el= item->el(i);
1669 1670
    Item_cache *tmp;
    if (!(tmp= values[i]= Item_cache::get_cache(el->result_type())))
1671
      return 1;
1672
    tmp->setup(el);
1673 1674 1675 1676 1677 1678 1679 1680
  }
  return 0;
}

void Item_cache_row::store(Item * item)
{
  null_value= 0;
  item->bring_value();
1681
  for (uint i= 0; i < item_count; i++)
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
  {
    values[i]->store(item->el(i));
    null_value|= values[i]->null_value;
  }
}

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);
  my_error(ER_CARDINALITY_COL, MYF(0), 1);
  DBUG_VOID_RETURN;
}

bool Item_cache_row::check_cols(uint c)
{
1699
  if (c != item_count)
1700 1701 1702 1703 1704 1705 1706 1707 1708
  {
    my_error(ER_CARDINALITY_COL, MYF(0), c);
    return 1;
  }
  return 0;
}

bool Item_cache_row::null_inside()
{
1709
  for (uint i= 0; i < item_count; i++)
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
  {
    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;
}

void Item_cache_row::bring_value()
{
1728
  for (uint i= 0; i < item_count; i++)
1729 1730 1731
    values[i]->bring_value();
  return;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1732 1733 1734 1735 1736 1737 1738 1739

/*****************************************************************************
** Instantiate templates
*****************************************************************************/

#ifdef __GNUC__
template class List<Item>;
template class List_iterator<Item>;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1740
template class List_iterator_fast<Item>;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1741 1742
template class List<List_item>;
#endif