Drizzled Public API Documentation

item.cc
00001 /* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
00002  *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
00003  *
00004  *  Copyright (C) 2008-2009 Sun Microsystems, Inc.
00005  *
00006  *  This program is free software; you can redistribute it and/or modify
00007  *  it under the terms of the GNU General Public License as published by
00008  *  the Free Software Foundation; version 2 of the License.
00009  *
00010  *  This program is distributed in the hope that it will be useful,
00011  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013  *  GNU General Public License for more details.
00014  *
00015  *  You should have received a copy of the GNU General Public License
00016  *  along with this program; if not, write to the Free Software
00017  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
00018  */
00019 
00020 #include <config.h>
00021 #include <drizzled/sql_select.h>
00022 #include <drizzled/error.h>
00023 #include <drizzled/show.h>
00024 #include <drizzled/item/cmpfunc.h>
00025 #include <drizzled/item/cache_row.h>
00026 #include <drizzled/item/type_holder.h>
00027 #include <drizzled/item/sum.h>
00028 #include <drizzled/item/copy_string.h>
00029 #include <drizzled/function/str/conv_charset.h>
00030 #include <drizzled/sql_base.h>
00031 #include <drizzled/util/convert.h>
00032 #include <drizzled/plugin/client.h>
00033 #include <drizzled/time_functions.h>
00034 #include <drizzled/field/str.h>
00035 #include <drizzled/field/num.h>
00036 #include <drizzled/field/blob.h>
00037 #include <drizzled/field/date.h>
00038 #include <drizzled/field/datetime.h>
00039 #include <drizzled/field/decimal.h>
00040 #include <drizzled/field/double.h>
00041 #include <drizzled/field/enum.h>
00042 #include <drizzled/field/epoch.h>
00043 #include <drizzled/field/int32.h>
00044 #include <drizzled/field/int64.h>
00045 #include <drizzled/field/microtime.h>
00046 #include <drizzled/field/null.h>
00047 #include <drizzled/field/real.h>
00048 #include <drizzled/field/size.h>
00049 #include <drizzled/field/time.h>
00050 #include <drizzled/field/varstring.h>
00051 #include <drizzled/current_session.h>
00052 #include <drizzled/session.h>
00053 #include <drizzled/internal/m_string.h>
00054 #include <drizzled/item/ref.h>
00055 #include <drizzled/item/subselect.h>
00056 #include <drizzled/sql_lex.h>
00057 #include <drizzled/system_variables.h>
00058 
00059 #include <cstdio>
00060 #include <math.h>
00061 #include <algorithm>
00062 #include <float.h>
00063 
00064 using namespace std;
00065 
00066 namespace drizzled {
00067 
00068 const String my_null_string("NULL", 4, default_charset_info);
00069 
00070 bool Item::is_expensive_processor(unsigned char *)
00071 {
00072   return false;
00073 }
00074 
00075 void Item::fix_after_pullout(Select_Lex *, Item **)
00076 {}
00077 
00078 Field *Item::tmp_table_field(Table *)
00079 {
00080   return NULL;
00081 }
00082 
00083 const char *Item::full_name(void) const
00084 {
00085   return name ? name : "???";
00086 }
00087 
00088 int64_t Item::val_int_endpoint(bool, bool *)
00089 {
00090   assert(0);
00091   return 0;
00092 }
00093 
00095 bool Item::val_bool()
00096 {
00097   switch(result_type()) 
00098   {
00099     case INT_RESULT:
00100       return val_int() != 0;
00101 
00102     case DECIMAL_RESULT:
00103     {
00104       type::Decimal decimal_value;
00105       type::Decimal *val= val_decimal(&decimal_value);
00106       if (val)
00107         return not val->isZero();
00108       return false;
00109     }
00110 
00111     case REAL_RESULT:
00112     case STRING_RESULT:
00113       return val_real() != 0.0;
00114 
00115     case ROW_RESULT:
00116       assert(0);
00117       abort();
00118   }
00119 
00120   assert(0);
00121   abort();
00122 }
00123 
00124 String *Item::val_string_from_real(String *str)
00125 {
00126   double nr= val_real();
00127   if (null_value)
00128     return NULL;
00129 
00130   str->set_real(nr, decimals, &my_charset_bin);
00131   return str;
00132 }
00133 
00134 String *Item::val_string_from_int(String *str)
00135 {
00136   int64_t nr= val_int();
00137   if (null_value)
00138     return NULL;
00139 
00140   str->set_int(nr, unsigned_flag, &my_charset_bin);
00141   return str;
00142 }
00143 
00144 String *Item::val_string_from_decimal(String *str)
00145 {
00146   type::Decimal dec_buf, *dec= val_decimal(&dec_buf);
00147   if (null_value)
00148     return NULL;
00149 
00150   class_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, false, &dec_buf);
00151   class_decimal2string(&dec_buf, 0, str);
00152   return str;
00153 }
00154 
00155 type::Decimal *Item::val_decimal_from_real(type::Decimal *decimal_value)
00156 {
00157   double nr= val_real();
00158   if (null_value)
00159     return NULL;
00160 
00161   double2_class_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
00162   return (decimal_value);
00163 }
00164 
00165 type::Decimal *Item::val_decimal_from_int(type::Decimal *decimal_value)
00166 {
00167   int64_t nr= val_int();
00168   if (null_value)
00169     return NULL;
00170 
00171   int2_class_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
00172   return decimal_value;
00173 }
00174 
00175 type::Decimal *Item::val_decimal_from_string(type::Decimal *decimal_value)
00176 {
00177   String *res;
00178   if (!(res= val_str(&str_value)))
00179     return NULL;
00180 
00181   if (decimal_value->store(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
00182                      res->ptr(), 
00183                      res->length(), 
00184                      res->charset()) & E_DEC_BAD_NUM)
00185   {
00186     push_warning_printf(&getSession(), 
00187                         DRIZZLE_ERROR::WARN_LEVEL_WARN,
00188                         ER_TRUNCATED_WRONG_VALUE,
00189                         ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
00190                         str_value.c_ptr());
00191   }
00192   return decimal_value;
00193 }
00194 
00195 type::Decimal *Item::val_decimal_from_date(type::Decimal *decimal_value)
00196 {
00197   assert(fixed);
00198   type::Time ltime;
00199   if (get_date(ltime, TIME_FUZZY_DATE))
00200   {
00201     decimal_value->set_zero();
00202     null_value= 1;                               // set NULL, stop processing
00203     return NULL;
00204   }
00205   return date2_class_decimal(&ltime, decimal_value);
00206 }
00207 
00208 type::Decimal *Item::val_decimal_from_time(type::Decimal *decimal_value)
00209 {
00210   assert(fixed);
00211   type::Time ltime;
00212   if (get_time(ltime))
00213   {
00214     decimal_value->set_zero();
00215     return NULL;
00216   }
00217   return date2_class_decimal(&ltime, decimal_value);
00218 }
00219 
00220 double Item::val_real_from_decimal()
00221 {
00222   /* Note that fix_fields may not be called for Item_avg_field items */
00223   double result;
00224   type::Decimal value_buff, *dec_val= val_decimal(&value_buff);
00225   if (null_value)
00226     return 0.0;
00227   class_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
00228   return result;
00229 }
00230 
00231 int64_t Item::val_int_from_decimal()
00232 {
00233   /* Note that fix_fields may not be called for Item_avg_field items */
00234   int64_t result;
00235   type::Decimal value, *dec_val= val_decimal(&value);
00236 
00237   if (null_value)
00238     return 0;
00239   dec_val->val_int32(E_DEC_FATAL_ERROR, unsigned_flag, &result);
00240 
00241   return result;
00242 }
00243 
00244 bool Item::save_time_in_field(Field *field)
00245 {
00246   type::Time ltime;
00247 
00248   if (get_time(ltime))
00249     return set_field_to_null(field);
00250 
00251   field->set_notnull();
00252 
00253   return field->store_time(ltime, type::DRIZZLE_TIMESTAMP_TIME);
00254 }
00255 
00256 bool Item::save_date_in_field(Field *field)
00257 {
00258   type::Time ltime;
00259 
00260   if (get_date(ltime, TIME_FUZZY_DATE))
00261     return set_field_to_null(field);
00262 
00263   field->set_notnull();
00264 
00265   return field->store_time(ltime, type::DRIZZLE_TIMESTAMP_DATETIME);
00266 }
00267 
00272 int Item::save_str_value_in_field(Field *field, String *result)
00273 {
00274   if (null_value)
00275     return set_field_to_null(field);
00276 
00277   field->set_notnull();
00278 
00279   return field->store(result->ptr(), result->length(), collation.collation);
00280 }
00281 
00282 Item::Item():
00283   is_expensive_cache(-1),
00284   name(0), 
00285   name_length(0),
00286   max_length(0), 
00287   marker(0),
00288   decimals(0),
00289   fixed(false),
00290   maybe_null(false),
00291   null_value(false),
00292   unsigned_flag(false), 
00293   with_sum_func(false),
00294   is_autogenerated_name(true),
00295   with_subselect(false),
00296   collation(&my_charset_bin, DERIVATION_COERCIBLE),
00297   _session(*current_session)
00298 {
00299   cmp_context= (Item_result)-1;
00300 
00301   /* Put item in free list so that we can free all items at end */
00302   next= getSession().free_list;
00303   getSession().free_list= this;
00304 
00305   /*
00306     Item constructor can be called during execution other then SQL_COM
00307     command => we should check session->lex().current_select on zero (session->lex
00308     can be uninitialised)
00309   */
00310   if (getSession().lex().current_select)
00311   {
00312     enum_parsing_place place= getSession().lex().current_select->parsing_place;
00313     if (place == SELECT_LIST || place == IN_HAVING)
00314       getSession().lex().current_select->select_n_having_items++;
00315   }
00316 }
00317 
00318 Item::Item(Session *session, Item *item):
00319   is_expensive_cache(-1),
00320   str_value(item->str_value),
00321   name(item->name),
00322   name_length(item->name_length),
00323   max_length(item->max_length),
00324   marker(item->marker),
00325   decimals(item->decimals),
00326   fixed(item->fixed),
00327   maybe_null(item->maybe_null),
00328   null_value(item->null_value),
00329   unsigned_flag(item->unsigned_flag),
00330   with_sum_func(item->with_sum_func),
00331   is_autogenerated_name(item->is_autogenerated_name),
00332   with_subselect(item->with_subselect),
00333   collation(item->collation),
00334   cmp_context(item->cmp_context),
00335   _session(*session)
00336 {
00337   /* Put this item in the session's free list */
00338   next= getSession().free_list;
00339   getSession().free_list= this;
00340 }
00341 
00342 uint32_t Item::float_length(uint32_t decimals_par) const
00343 {
00344   return decimals != NOT_FIXED_DEC ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;
00345 }
00346 
00347 uint32_t Item::decimal_precision() const
00348 {
00349   Item_result restype= result_type();
00350 
00351   if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
00352     return min(class_decimal_length_to_precision(max_length, decimals, unsigned_flag),
00353                (uint32_t) DECIMAL_MAX_PRECISION);
00354   return min(max_length, (uint32_t) DECIMAL_MAX_PRECISION);
00355 }
00356 
00357 int Item::decimal_int_part() const
00358 {
00359   return class_decimal_int_part(decimal_precision(), decimals);
00360 }
00361 
00362 void Item::print(String *str)
00363 {
00364   str->append(full_name());
00365 }
00366 
00367 void Item::print_item_w_name(String *str)
00368 {
00369   print(str);
00370 
00371   if (name)
00372   {
00373     str->append(STRING_WITH_LEN(" AS "));
00374     str->append_identifier(str_ref(name));
00375   }
00376 }
00377 
00378 void Item::split_sum_func(Session *, Item **, List<Item> &)
00379 {}
00380 
00381 void Item::cleanup()
00382 {
00383   fixed= false;
00384   marker= 0;
00385 }
00386 
00387 Item* Item::transform(Item_transformer transformer, unsigned char *arg)
00388 {
00389   return (this->*transformer)(arg);
00390 }
00391 
00392 bool Item::check_cols(uint32_t c)
00393 {
00394   if (c != 1)
00395   {
00396     my_error(ER_OPERAND_COLUMNS, MYF(0), c);
00397     return true;
00398   }
00399   return false;
00400 }
00401 
00402 void Item::set_name(const char *str, uint32_t length, const charset_info_st* cs)
00403 {
00404   if (not length)
00405   {
00406     if (0) // str && *str)
00407       std::cerr << "non-empty empty name: " << str << std::endl;
00408     /* Empty string, used by AS or internal function like last_insert_id() */
00409     name= str; // should be NULL (or "");
00410     name_length= 0;
00411     return;
00412   }
00413   if (cs->ctype)
00414   {
00415     uint32_t orig_len= length;
00416     while (length && not cs->isgraph(*str))
00417     {
00418       /* Fix problem with yacc */
00419       length--;
00420       str++;
00421     }
00422     if (orig_len != length && not is_autogenerated_name)
00423     {
00424       if (length == 0)
00425         push_warning_printf(&getSession(), DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NAME_BECOMES_EMPTY, ER(ER_NAME_BECOMES_EMPTY), str + length - orig_len);
00426       else
00427         push_warning_printf(&getSession(), DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_REMOVED_SPACES, ER(ER_REMOVED_SPACES), str + length - orig_len);
00428     }
00429   }
00430   name= memory::sql_strdup(str_ref(str, length));
00431 }
00432 
00433 bool Item::eq(const Item *item, bool) const
00434 {
00435   /*
00436     Note, that this is never true if item is a Item_param:
00437     for all basic constants we have special checks, and Item_param's
00438     type() can be only among basic constant types.
00439   */
00440   return type() == item->type() && 
00441          name && 
00442          item->name &&
00443          not system_charset_info->strcasecmp(name, item->name);
00444 }
00445 
00446 Item *Item::safe_charset_converter(const charset_info_st* tocs)
00447 {
00448   Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1);
00449   return conv->safe ? conv : NULL; // memory leak? (conv if not conv->safe)
00450 }
00451 
00452 bool Item::get_date(type::Time &ltime,uint32_t fuzzydate)
00453 {
00454   do
00455   {
00456     if (is_null())
00457     {
00458       break;
00459     }
00460     else if (result_type() == STRING_RESULT)
00461     {
00462       char buff[type::Time::MAX_STRING_LENGTH];
00463       String tmp(buff,sizeof(buff), &my_charset_bin);
00464       String *res= val_str(&tmp);
00465       if (not res || str_to_datetime_with_warn(getSession(), *res, ltime, fuzzydate) <= type::DRIZZLE_TIMESTAMP_ERROR)
00466       {
00467         break;
00468       }
00469     }
00470     else
00471     {
00472       int64_t value= val_int();
00473       type::datetime_t date_value;
00474 
00475       ltime.convert(date_value, value, fuzzydate);
00476 
00477       if (not type::is_valid(date_value))
00478       {
00479         char buff[DECIMAL_LONGLONG_DIGITS];
00480         char* end= internal::int64_t10_to_str(value, buff, -10);
00481         make_truncated_value_warning(getSession(), DRIZZLE_ERROR::WARN_LEVEL_WARN, str_ref(buff, (int) (end-buff)), type::DRIZZLE_TIMESTAMP_NONE, NULL);
00482         break;
00483       }
00484     }
00485 
00486     return false;
00487   } while (0);
00488 
00489   ltime.reset();
00490 
00491   return true;
00492 }
00493 
00494 bool Item::get_time(type::Time &ltime)
00495 {
00496   char buff[type::Time::MAX_STRING_LENGTH];
00497   String tmp(buff,sizeof(buff),&my_charset_bin);
00498   String *res= val_str(&tmp);
00499   if (not res || str_to_time_with_warn(getSession(), *res, ltime))
00500   {
00501     ltime.reset();
00502     return true;
00503   }
00504 
00505   return false;
00506 }
00507 
00508 bool Item::get_date_result(type::Time &ltime,uint32_t fuzzydate)
00509 {
00510   return get_date(ltime, fuzzydate);
00511 }
00512 
00513 bool Item::is_null()
00514 {
00515   return false;
00516 }
00517 
00518 void Item::update_null_value ()
00519 {
00520   (void) val_int();
00521 }
00522 
00523 void Item::top_level_item(void)
00524 {}
00525 
00526 void Item::set_result_field(Field *)
00527 {}
00528 
00529 bool Item::is_result_field(void)
00530 {
00531   return false;
00532 }
00533 
00534 bool Item::is_bool_func(void)
00535 {
00536   return false;
00537 }
00538 
00539 void Item::save_in_result_field(bool)
00540 {}
00541 
00542 void Item::no_rows_in_result(void)
00543 {}
00544 
00545 Item *Item::copy_or_same(Session *)
00546 {
00547   return this;
00548 }
00549 
00550 Item *Item::copy_andor_structure(Session *)
00551 {
00552   return this;
00553 }
00554 
00555 Item *Item::real_item(void)
00556 {
00557   return this;
00558 }
00559 
00560 const Item *Item::real_item(void) const
00561 {
00562   return this;
00563 }
00564 
00565 Item *Item::get_tmp_table_item(Session *session)
00566 {
00567   return copy_or_same(session);
00568 }
00569 
00570 const charset_info_st *Item::default_charset()
00571 {
00572   return current_session->variables.getCollation();
00573 }
00574 
00575 const charset_info_st *Item::compare_collation()
00576 {
00577   return NULL;
00578 }
00579 
00580 bool Item::walk(Item_processor processor, bool, unsigned char *arg)
00581 {
00582   return (this->*processor)(arg);
00583 }
00584 
00585 Item* Item::compile(Item_analyzer analyzer, unsigned char **arg_p, Item_transformer transformer, unsigned char *arg_t)
00586 {
00587   return (this->*analyzer)(arg_p)
00588     ? (this->*transformer)(arg_t)
00589     : NULL;
00590 }
00591 
00592 void Item::traverse_cond(Cond_traverser traverser, void *arg, traverse_order)
00593 {
00594   (*traverser)(this, arg);
00595 }
00596 
00597 bool Item::remove_dependence_processor(unsigned char *)
00598 {
00599   return false;
00600 }
00601 
00602 bool Item::collect_item_field_processor(unsigned char *)
00603 {
00604   return false;
00605 }
00606 
00607 bool Item::find_item_in_field_list_processor(unsigned char *)
00608 {
00609   return false;
00610 }
00611 
00612 bool Item::change_context_processor(unsigned char *)
00613 {
00614   return false;
00615 }
00616 
00617 bool Item::register_field_in_read_map(unsigned char *)
00618 {
00619   return false;
00620 }
00621 
00622 bool Item::subst_argument_checker(unsigned char **arg)
00623 {
00624   if (*arg)
00625     *arg= NULL;
00626   return true;
00627 }
00628 
00629 Item *Item::equal_fields_propagator(unsigned char *)
00630 {
00631   return this;
00632 }
00633 
00634 bool Item::set_no_const_sub(unsigned char *)
00635 {
00636   return false;
00637 }
00638 
00639 Item *Item::replace_equal_field(unsigned char *)
00640 {
00641   return this;
00642 }
00643 
00644 uint32_t Item::cols()
00645 {
00646   return 1;
00647 }
00648 
00649 Item* Item::element_index(uint32_t)
00650 {
00651   return this;
00652 }
00653 
00654 Item** Item::addr(uint32_t)
00655 {
00656   return NULL;
00657 }
00658 
00659 bool Item::null_inside()
00660 {
00661   return false;
00662 }
00663 
00664 void Item::bring_value()
00665 {}
00666 
00667 Item *Item::neg_transformer(Session *)
00668 {
00669   return NULL;
00670 }
00671 
00672 Item *Item::update_value_transformer(unsigned char *)
00673 {
00674   return this;
00675 }
00676 
00677 void Item::delete_self()
00678 {
00679   cleanup();
00680   delete this;
00681 }
00682 
00683 bool Item::result_as_int64_t()
00684 {
00685   return false;
00686 }
00687 
00688 bool Item::is_expensive()
00689 {
00690   if (is_expensive_cache < 0)
00691     is_expensive_cache= walk(&Item::is_expensive_processor, 0, NULL);
00692   return test(is_expensive_cache);
00693 }
00694 
00695 /*
00696  need a special class to adjust printing : references to aggregate functions
00697  must not be printed as refs because the aggregate functions that are added to
00698  the front of select list are not printed as well.
00699 */
00700 class Item_aggregate_ref : public Item_ref
00701 {
00702 public:
00703   Item_aggregate_ref(Name_resolution_context *context_arg, Item **item,
00704                   const char *table_name_arg, const char *field_name_arg)
00705     :Item_ref(context_arg, item, table_name_arg, field_name_arg) {}
00706 
00707   virtual inline void print (String *str)
00708   {
00709     if (ref)
00710       (*ref)->print(str);
00711     else
00712       Item_ident::print(str);
00713   }
00714 };
00715 
00716 void Item::split_sum_func(Session *session, Item **ref_pointer_array,
00717                           List<Item> &fields, Item **ref,
00718                           bool skip_registered)
00719 {
00720   /* An item of type Item_sum  is registered <=> ref_by != 0 */
00721   if (type() == SUM_FUNC_ITEM && 
00722       skip_registered &&
00723       ((Item_sum *) this)->ref_by)
00724     return;
00725 
00726   if ((type() != SUM_FUNC_ITEM && with_sum_func) ||
00727       (type() == FUNC_ITEM &&
00728        (((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC ||
00729         ((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC)))
00730   {
00731     /* Will split complicated items and ignore simple ones */
00732     split_sum_func(session, ref_pointer_array, fields);
00733   }
00734   else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) &&
00735            type() != SUBSELECT_ITEM &&
00736            type() != REF_ITEM)
00737   {
00738     /*
00739       Replace item with a reference so that we can easily calculate
00740       it (in case of sum functions) or copy it (in case of fields)
00741 
00742       The test above is to ensure we don't do a reference for things
00743       that are constants (PARAM_TABLE_BIT is in effect a constant)
00744       or already referenced (for example an item in HAVING)
00745       Exception is Item_direct_view_ref which we need to convert to
00746       Item_ref to allow fields from view being stored in tmp table.
00747     */
00748     Item_aggregate_ref *item_ref;
00749     uint32_t el= fields.size();
00750     Item *real_itm= real_item();
00751 
00752     ref_pointer_array[el]= real_itm;
00753     item_ref= new Item_aggregate_ref(&session->lex().current_select->context, ref_pointer_array + el, 0, name);
00754     if (type() == SUM_FUNC_ITEM)
00755       item_ref->depended_from= ((Item_sum *) this)->depended_from();
00756     fields.push_front(real_itm);
00757     *ref= item_ref;
00758   }
00759 }
00760 
00761 /*
00762   Functions to convert item to field (for send_fields)
00763 */
00764 bool Item::fix_fields(Session *, Item **)
00765 {
00766   /* We do not check fields which are fixed during construction */
00767   assert(! fixed || basic_const_item());
00768   fixed= true;
00769   return false;
00770 }
00771 
00772 void mark_as_dependent(Session *session, Select_Lex *last, Select_Lex *current,
00773                               Item_ident *resolved_item,
00774                               Item_ident *mark_item)
00775 {
00776   const char *db_name= (resolved_item->db_name ?
00777                         resolved_item->db_name : "");
00778   const char *table_name= (resolved_item->table_name ?
00779                            resolved_item->table_name : "");
00780   /* store pointer on Select_Lex from which item is dependent */
00781   if (mark_item)
00782     mark_item->depended_from= last;
00783   current->mark_as_dependent(last);
00784   if (session->lex().describe & DESCRIBE_EXTENDED)
00785   {
00786     char warn_buff[DRIZZLE_ERRMSG_SIZE];
00787     snprintf(warn_buff, sizeof(warn_buff), ER(ER_WARN_FIELD_RESOLVED),
00788             db_name, (db_name[0] ? "." : ""),
00789             table_name, (table_name [0] ? "." : ""),
00790             resolved_item->field_name,
00791       current->select_number, last->select_number);
00792     push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
00793      ER_WARN_FIELD_RESOLVED, warn_buff);
00794   }
00795 }
00796 
00797 void mark_select_range_as_dependent(Session *session,
00798                                     Select_Lex *last_select,
00799                                     Select_Lex *current_sel,
00800                                     Field *found_field, Item *found_item,
00801                                     Item_ident *resolved_item)
00802 {
00803   /*
00804     Go from current SELECT to SELECT where field was resolved (it
00805     have to be reachable from current SELECT, because it was already
00806     done once when we resolved this field and cached result of
00807     resolving)
00808   */
00809   Select_Lex *previous_select= current_sel;
00810   for (; previous_select->outer_select() != last_select;
00811        previous_select= previous_select->outer_select())
00812   {
00813     Item_subselect *prev_subselect_item= previous_select->master_unit()->item;
00814     prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
00815     prev_subselect_item->const_item_cache= false;
00816   }
00817   {
00818     Item_subselect *prev_subselect_item= previous_select->master_unit()->item;
00819     Item_ident *dependent= resolved_item;
00820     if (found_field == view_ref_found)
00821     {
00822       Item::Type type= found_item->type();
00823       prev_subselect_item->used_tables_cache|= found_item->used_tables();
00824       dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
00825                   (Item_ident*) found_item :
00826                   0);
00827     }
00828     else
00829       prev_subselect_item->used_tables_cache|= found_field->getTable()->map;
00830     prev_subselect_item->const_item_cache= false;
00831     mark_as_dependent(session, last_select, current_sel, resolved_item,
00832                       dependent);
00833   }
00834 }
00835 
00850 static Item** find_field_in_group_list(Session *session, Item *find_item, Order *group_list)
00851 {
00852   const char *db_name;
00853   const char *table_name;
00854   const char *field_name;
00855   Order *found_group= NULL;
00856   int found_match_degree= 0;
00857   Item_ident *cur_field;
00858   int cur_match_degree= 0;
00859   char name_buff[NAME_LEN+1];
00860 
00861   if (find_item->type() == Item::FIELD_ITEM ||
00862       find_item->type() == Item::REF_ITEM)
00863   {
00864     db_name= ((Item_ident*) find_item)->db_name;
00865     table_name= ((Item_ident*) find_item)->table_name;
00866     field_name= ((Item_ident*) find_item)->field_name;
00867   }
00868   else
00869     return NULL;
00870 
00871   if (db_name)
00872   {
00873     /* Convert database to lower case for comparison */
00874     strncpy(name_buff, db_name, sizeof(name_buff)-1);
00875     files_charset_info->casedn_str(name_buff);
00876     db_name= name_buff;
00877   }
00878 
00879   assert(field_name != 0);
00880 
00881   for (Order *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
00882   {
00883     if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM)
00884     {
00885       cur_field= (Item_ident*) *cur_group->item;
00886       cur_match_degree= 0;
00887 
00888       assert(cur_field->field_name != 0);
00889 
00890       if (system_charset_info->strcasecmp(cur_field->field_name, field_name))
00891         continue;
00892       ++cur_match_degree;
00893 
00894       if (cur_field->table_name && table_name)
00895       {
00896         /* If field_name is qualified by a table name. */
00897         if (table_alias_charset->strcasecmp(cur_field->table_name, table_name))
00898           /* Same field names, different tables. */
00899           return NULL;
00900 
00901         ++cur_match_degree;
00902         if (cur_field->db_name && db_name)
00903         {
00904           /* If field_name is also qualified by a database name. */
00905           if (system_charset_info->strcasecmp(cur_field->db_name, db_name))
00906           {
00907             /* Same field names, different databases. */
00908             return NULL;
00909           }
00910           ++cur_match_degree;
00911         }
00912       }
00913 
00914       if (cur_match_degree > found_match_degree)
00915       {
00916         found_match_degree= cur_match_degree;
00917         found_group= cur_group;
00918       }
00919       else if (found_group &&
00920                (cur_match_degree == found_match_degree) &&
00921                ! (*(found_group->item))->eq(cur_field, 0))
00922       {
00923         /*
00924           If the current resolve candidate matches equally well as the current
00925           best match, they must reference the same column, otherwise the field
00926           is ambiguous.
00927         */
00928         my_error(ER_NON_UNIQ_ERROR, MYF(0), find_item->full_name(), session->where());
00929         return NULL;
00930       }
00931     }
00932   }
00933 
00934   if (found_group)
00935     return found_group->item;
00936 
00937   return NULL;
00938 }
00939 
00940 Item** resolve_ref_in_select_and_group(Session *session, Item_ident *ref, Select_Lex *select)
00941 {
00942   Item **group_by_ref= NULL;
00943   Item **select_ref= NULL;
00944   Order *group_list= (Order*) select->group_list.first;
00945   bool ambiguous_fields= false;
00946   uint32_t counter;
00947   enum_resolution_type resolution;
00948 
00949   /*
00950     Search for a column or derived column named as 'ref' in the SELECT
00951     clause of the current select.
00952   */
00953   if (!(select_ref= find_item_in_list(session,
00954                                       ref, *(select->get_item_list()),
00955                                       &counter, REPORT_EXCEPT_NOT_FOUND,
00956                                       &resolution)))
00957     return NULL; /* Some error occurred. */
00958   if (resolution == RESOLVED_AGAINST_ALIAS)
00959     ref->alias_name_used= true;
00960 
00961   /* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
00962   if (select->having_fix_field && !ref->with_sum_func && group_list)
00963   {
00964     group_by_ref= find_field_in_group_list(session, ref, group_list);
00965 
00966     /* Check if the fields found in SELECT and GROUP BY are the same field. */
00967     if (group_by_ref && (select_ref != not_found_item) &&
00968         !((*group_by_ref)->eq(*select_ref, 0)))
00969     {
00970       ambiguous_fields= true;
00971       push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
00972                           ER(ER_NON_UNIQ_ERROR), ref->full_name(),
00973                           session->where());
00974 
00975     }
00976   }
00977 
00978   if (select_ref != not_found_item || group_by_ref)
00979   {
00980     if (select_ref != not_found_item && !ambiguous_fields)
00981     {
00982       assert(*select_ref != 0);
00983       if (!select->ref_pointer_array[counter])
00984       {
00985         my_error(ER_ILLEGAL_REFERENCE, MYF(0),
00986                  ref->name, "forward reference in item list");
00987         return NULL;
00988       }
00989       assert((*select_ref)->fixed);
00990       return (select->ref_pointer_array + counter);
00991     }
00992     if (group_by_ref)
00993       return group_by_ref;
00994     assert(false);
00995     return NULL; /* So there is no compiler warning. */
00996   }
00997 
00998   return (Item**) not_found_item;
00999 }
01000 
01001 void Item::init_make_field(SendField *tmp_field, enum_field_types field_type_arg)
01002 {
01003   tmp_field->db_name= "";
01004   tmp_field->org_table_name= "";
01005   tmp_field->org_col_name= "";
01006   tmp_field->table_name= "";
01007   tmp_field->col_name= name;
01008   tmp_field->charsetnr= collation.collation->number;
01009   tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) | (collation.collation->binary_compare() ? BINARY_FLAG : 0);
01010   tmp_field->type= field_type_arg;
01011   tmp_field->length= max_length;
01012   tmp_field->decimals= decimals;
01013 }
01014 
01015 void Item::make_field(SendField *tmp_field)
01016 {
01017   init_make_field(tmp_field, field_type());
01018 }
01019 
01020 enum_field_types Item::string_field_type() const
01021 {
01022   enum_field_types f_type= DRIZZLE_TYPE_VARCHAR;
01023   if (max_length >= 65536)
01024     f_type= DRIZZLE_TYPE_BLOB;
01025   return f_type;
01026 }
01027 
01028 enum_field_types Item::field_type() const
01029 {
01030   switch (result_type()) {
01031   case STRING_RESULT:  
01032     return string_field_type();
01033   case INT_RESULT:     
01034     return DRIZZLE_TYPE_LONGLONG;
01035   case DECIMAL_RESULT: 
01036     return DRIZZLE_TYPE_DECIMAL;
01037   case REAL_RESULT:    
01038     return DRIZZLE_TYPE_DOUBLE;
01039   case ROW_RESULT:
01040     assert(0);
01041   }
01042 
01043   abort();
01044 }
01045 
01046 bool Item::is_datetime()
01047 {
01048   return field::isDateTime(field_type());
01049 }
01050 
01051 String *Item::check_well_formed_result(String *str, bool send_error)
01052 {
01053   /* Check whether we got a well-formed string */
01054   const charset_info_st * const cs= str->charset();
01055   int well_formed_error;
01056   uint32_t wlen= cs->cset->well_formed_len(*cs, *str, str->length(), &well_formed_error);
01057   if (wlen < str->length())
01058   {
01059     char hexbuf[7];
01060     enum DRIZZLE_ERROR::enum_warning_level level;
01061     uint32_t diff= str->length() - wlen;
01062     set_if_smaller(diff, 3U);
01063     (void) drizzled_string_to_hex(hexbuf, str->ptr() + wlen, diff);
01064     if (send_error)
01065     {
01066       my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
01067                cs->csname,  hexbuf);
01068       return NULL;
01069     }
01070     {
01071       level= DRIZZLE_ERROR::WARN_LEVEL_ERROR;
01072       null_value= 1;
01073       str= 0;
01074     }
01075     push_warning_printf(&getSession(), level, ER_INVALID_CHARACTER_STRING,
01076                         ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
01077   }
01078   return str;
01079 }
01080 
01081 bool Item::eq_by_collation(Item *item, bool binary_cmp, const charset_info_st * const cs)
01082 {
01083   const charset_info_st *save_cs= 0;
01084   const charset_info_st *save_item_cs= 0;
01085   if (collation.collation != cs)
01086   {
01087     save_cs= collation.collation;
01088     collation.collation= cs;
01089   }
01090   if (item->collation.collation != cs)
01091   {
01092     save_item_cs= item->collation.collation;
01093     item->collation.collation= cs;
01094   }
01095   bool res= eq(item, binary_cmp);
01096   if (save_cs)
01097     collation.collation= save_cs;
01098   if (save_item_cs)
01099     item->collation.collation= save_item_cs;
01100   return res;
01101 }
01102 
01103 Field *Item::make_string_field(Table *table)
01104 {
01105   Field *field;
01106   assert(collation.collation);
01107   if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB)
01108   {
01109     field= new Field_blob(max_length, maybe_null, name,
01110                           collation.collation);
01111   }
01112   else
01113   {
01114     table->setVariableWidth();
01115     field= new Field_varstring(max_length, maybe_null, name,
01116                                collation.collation);
01117   }
01118 
01119   if (field)
01120     field->init(table);
01121   return field;
01122 }
01123 
01124 Field *Item::tmp_table_field_from_field_type(Table *table, bool)
01125 {
01126   /*
01127     The field functions defines a field to be not null if null_ptr is not 0
01128   */
01129   unsigned char *null_ptr= maybe_null ? (unsigned char*) "" : 0;
01130   Field *field= NULL;
01131 
01132   switch (field_type()) {
01133   case DRIZZLE_TYPE_DECIMAL:
01134     field= new Field_decimal((unsigned char*) 0,
01135                                  max_length,
01136                                  null_ptr,
01137                                  0,
01138                                  Field::NONE,
01139                                  name,
01140                                  decimals);
01141     break;
01142   case DRIZZLE_TYPE_LONG:
01143     field= new field::Int32((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE, name);
01144     break;
01145   case DRIZZLE_TYPE_LONGLONG:
01146     field= new field::Int64((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE, name);
01147     break;
01148   case DRIZZLE_TYPE_DOUBLE:
01149     field= new Field_double((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE,
01150                             name, decimals, 0, unsigned_flag);
01151     break;
01152   case DRIZZLE_TYPE_NULL:
01153     field= new Field_null((unsigned char*) 0, max_length, name);
01154     break;
01155   case DRIZZLE_TYPE_DATE:
01156     field= new Field_date(maybe_null, name);
01157     break;
01158 
01159   case DRIZZLE_TYPE_MICROTIME:
01160     field= new field::Microtime(maybe_null, name);
01161     break;
01162 
01163   case DRIZZLE_TYPE_TIMESTAMP:
01164     field= new field::Epoch(maybe_null, name);
01165     break;
01166   case DRIZZLE_TYPE_DATETIME:
01167     field= new Field_datetime(maybe_null, name);
01168     break;
01169   case DRIZZLE_TYPE_TIME:
01170     field= new field::Time(maybe_null, name);
01171     break;
01172   case DRIZZLE_TYPE_BOOLEAN:
01173   case DRIZZLE_TYPE_UUID:
01174   case DRIZZLE_TYPE_IPV6:
01175   case DRIZZLE_TYPE_ENUM:
01176   case DRIZZLE_TYPE_VARCHAR:
01177     return make_string_field(table);
01178   case DRIZZLE_TYPE_BLOB:
01179       field= new Field_blob(max_length, maybe_null, name, collation.collation);
01180     break;          // Blob handled outside of case
01181   }
01182   assert(field);
01183 
01184   if (field)
01185     field->init(table);
01186   return field;
01187 }
01188 
01189 /*
01190   This implementation can lose str_value content, so if the
01191   Item uses str_value to store something, it should
01192   reimplement it's ::save_in_field() as Item_string, for example, does
01193 */
01194 int Item::save_in_field(Field *field, bool no_conversions)
01195 {
01196   int error;
01197   if (result_type() == STRING_RESULT)
01198   {
01199     String *result;
01200     const charset_info_st * const cs= collation.collation;
01201     char buff[MAX_FIELD_WIDTH];   // Alloc buffer for small columns
01202     str_value.set_quick(buff, sizeof(buff), cs);
01203     result=val_str(&str_value);
01204     if (null_value)
01205     {
01206       str_value.set_quick(0, 0, cs);
01207       return set_field_to_null_with_conversions(field, no_conversions);
01208     }
01209 
01210     /* NOTE: If null_value == false, "result" must be not NULL.  */
01211 
01212     field->set_notnull();
01213     error=field->store(result->ptr(),result->length(),cs);
01214     str_value.set_quick(0, 0, cs);
01215   }
01216   else if (result_type() == REAL_RESULT &&
01217            field->result_type() == STRING_RESULT)
01218   {
01219     double nr= val_real();
01220     if (null_value)
01221       return set_field_to_null_with_conversions(field, no_conversions);
01222     field->set_notnull();
01223     error= field->store(nr);
01224   }
01225   else if (result_type() == REAL_RESULT)
01226   {
01227     double nr= val_real();
01228     if (null_value)
01229       return set_field_to_null(field);
01230     field->set_notnull();
01231     error=field->store(nr);
01232   }
01233   else if (result_type() == DECIMAL_RESULT)
01234   {
01235     type::Decimal decimal_value;
01236     type::Decimal *value= val_decimal(&decimal_value);
01237     if (null_value)
01238       return set_field_to_null_with_conversions(field, no_conversions);
01239     field->set_notnull();
01240     error=field->store_decimal(value);
01241   }
01242   else
01243   {
01244     int64_t nr=val_int();
01245     if (null_value)
01246       return set_field_to_null_with_conversions(field, no_conversions);
01247     field->set_notnull();
01248     error=field->store(nr, unsigned_flag);
01249   }
01250   return error;
01251 }
01252 
01262 bool Item::cache_const_expr_analyzer(unsigned char **arg)
01263 {
01264   bool *cache_flag= (bool*)*arg;
01265   if (!*cache_flag)
01266   {
01267     Item *item= real_item();
01268     /*
01269       Cache constant items unless it's a basic constant, constant field or
01270       a subselect (they use their own cache).
01271     */
01272     if (const_item() &&
01273         !(item->basic_const_item() || item->type() == Item::FIELD_ITEM ||
01274           item->type() == SUBSELECT_ITEM ||
01275            /*
01276              Do not cache GET_USER_VAR() function as its const_item() may
01277              return TRUE for the current thread but it still may change
01278              during the execution.
01279            */
01280           (item->type() == Item::FUNC_ITEM &&
01281            ((Item_func*)item)->functype() == Item_func::GUSERVAR_FUNC)))
01282       *cache_flag= true;
01283     return true;
01284   }
01285   return false;
01286 }
01287 
01297 Item* Item::cache_const_expr_transformer(unsigned char *arg)
01298 {
01299   if (*(bool*)arg)
01300   {
01301     *((bool*)arg)= false;
01302     Item_cache *cache= Item_cache::get_cache(this);
01303     if (!cache)
01304       return NULL;
01305     cache->setup(this);
01306     cache->store(this);
01307     return cache;
01308   }
01309   return this;
01310 }
01311 
01312 void Item::send(plugin::Client *client, String *buffer)
01313 {
01314   switch (field_type())
01315   {
01316   case DRIZZLE_TYPE_DATE:
01317   case DRIZZLE_TYPE_NULL:
01318   case DRIZZLE_TYPE_ENUM:
01319   case DRIZZLE_TYPE_BLOB:
01320   case DRIZZLE_TYPE_VARCHAR:
01321   case DRIZZLE_TYPE_BOOLEAN:
01322   case DRIZZLE_TYPE_UUID:
01323   case DRIZZLE_TYPE_IPV6:
01324   case DRIZZLE_TYPE_DECIMAL:
01325     {
01326       if (String* res=val_str(buffer))
01327         client->store(res->ptr(), res->length());
01328       break;
01329     }
01330   case DRIZZLE_TYPE_LONG:
01331     {
01332       int64_t nr= val_int();
01333       if (!null_value)
01334         client->store((int32_t)nr);
01335       break;
01336     }
01337   case DRIZZLE_TYPE_LONGLONG:
01338     {
01339       int64_t nr= val_int();
01340       if (!null_value)
01341       {
01342         if (unsigned_flag)
01343           client->store((uint64_t)nr);
01344         else
01345           client->store((int64_t)nr);
01346       }
01347       break;
01348     }
01349   case DRIZZLE_TYPE_DOUBLE:
01350     {
01351       double nr= val_real();
01352       if (!null_value)
01353         client->store(nr, decimals, buffer);
01354       break;
01355     }
01356   case DRIZZLE_TYPE_TIME:
01357     {
01358       type::Time tm;
01359       get_time(tm);
01360       if (not null_value)
01361         client->store(&tm);
01362       break;
01363     }
01364   case DRIZZLE_TYPE_DATETIME:
01365   case DRIZZLE_TYPE_MICROTIME:
01366   case DRIZZLE_TYPE_TIMESTAMP:
01367     {
01368       type::Time tm;
01369       get_date(tm, TIME_FUZZY_DATE);
01370       if (!null_value)
01371         client->store(&tm);
01372       break;
01373     }
01374   }
01375   if (null_value)
01376     client->store();
01377 }
01378 
01379 uint32_t Item::max_char_length() const
01380 {
01381   return max_length / collation.collation->mbmaxlen;
01382 }
01383 
01384 void Item::fix_char_length(uint32_t max_char_length_arg)
01385 { 
01386   max_length= char_to_byte_length_safe(max_char_length_arg, collation.collation->mbmaxlen);
01387 }
01388 
01389 Item_result item_cmp_type(Item_result a,Item_result b)
01390 {
01391   if (a == STRING_RESULT && b == STRING_RESULT)
01392     return STRING_RESULT;
01393 
01394   if (a == INT_RESULT && b == INT_RESULT)
01395     return INT_RESULT;
01396   else if (a == ROW_RESULT || b == ROW_RESULT)
01397     return ROW_RESULT;
01398 
01399   if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
01400       (b == INT_RESULT || b == DECIMAL_RESULT))
01401     return DECIMAL_RESULT;
01402 
01403   return REAL_RESULT;
01404 }
01405 
01406 void resolve_const_item(Session *session, Item **ref, Item *comp_item)
01407 {
01408   Item *item= *ref;
01409   Item *new_item= NULL;
01410   if (item->basic_const_item())
01411     return; /* Can't be better */
01412   Item_result res_type=item_cmp_type(comp_item->result_type(), item->result_type());
01413   const char *name=item->name; /* Alloced by memory::sql_alloc */
01414 
01415   switch (res_type) 
01416   {
01417   case STRING_RESULT:
01418     {
01419       char buff[MAX_FIELD_WIDTH];
01420       String tmp(buff,sizeof(buff),&my_charset_bin),*result;
01421       result=item->val_str(&tmp);
01422       if (item->null_value)
01423         new_item= new Item_null(name);
01424       else
01425         new_item= new Item_string(name, memory::sql_strdup(*result), result->length(), result->charset());
01426       break;
01427     }
01428   case INT_RESULT:
01429     {
01430       new_item= item->null_value ? (Item*)new Item_null(name) : (Item*)new Item_int(name, item->val_int(), item->max_length);
01431       break;
01432     }
01433   case ROW_RESULT:
01434     if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
01435     {
01436       /*
01437         Substitute constants only in Item_rows. Don't affect other Items
01438         with ROW_RESULT (eg Item_singlerow_subselect).
01439 
01440         For such Items more optimal is to detect if it is constant and replace
01441         it with Item_row. This would optimize queries like this:
01442         SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
01443       */
01444       Item_row *item_row= (Item_row*) item;
01445       Item_row *comp_item_row= (Item_row*) comp_item;
01446       new_item= 0;
01447       /*
01448         If item and comp_item are both Item_rows and have same number of cols
01449         then process items in Item_row one by one.
01450         We can't ignore NULL values here as this item may be used with <=>, in
01451         which case NULL's are significant.
01452       */
01453       assert(item->result_type() == comp_item->result_type());
01454       assert(item_row->cols() == comp_item_row->cols());
01455       for (uint32_t col= item_row->cols(); col--; )
01456         resolve_const_item(session, item_row->addr(col), comp_item_row->element_index(col));
01457       break;
01458     }
01459     /* Fallthrough */
01460   case REAL_RESULT:
01461     {           // It must REAL_RESULT
01462       double result= item->val_real();
01463       uint32_t length=item->max_length,decimals=item->decimals;
01464       bool null_value=item->null_value;
01465       new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
01466                  new Item_float(name, result, decimals, length));
01467       break;
01468     }
01469   case DECIMAL_RESULT:
01470     {
01471       type::Decimal decimal_value;
01472       type::Decimal *result= item->val_decimal(&decimal_value);
01473       uint32_t length= item->max_length, decimals= item->decimals;
01474       bool null_value= item->null_value;
01475       new_item= (null_value ?
01476                  (Item*) new Item_null(name) :
01477                  (Item*) new Item_decimal(name, result, length, decimals));
01478       break;
01479     }
01480   }
01481 
01482   if (new_item)
01483     *ref= new_item;
01484 }
01485 
01486 bool field_is_equal_to_item(Field *field,Item *item)
01487 {
01488 
01489   Item_result res_type=item_cmp_type(field->result_type(),
01490              item->result_type());
01491   if (res_type == STRING_RESULT)
01492   {
01493     char item_buff[MAX_FIELD_WIDTH];
01494     char field_buff[MAX_FIELD_WIDTH];
01495     String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result;
01496     String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
01497     item_result=item->val_str(&item_tmp);
01498     if (item->null_value)
01499       return 1;         // This must be true
01500     field->val_str_internal(&field_tmp);
01501     return not stringcmp(&field_tmp,item_result);
01502   }
01503 
01504   if (res_type == INT_RESULT)
01505     return 1;         // Both where of type int
01506 
01507   if (res_type == DECIMAL_RESULT)
01508   {
01509     type::Decimal item_buf, *item_val,
01510                field_buf, *field_val;
01511     item_val= item->val_decimal(&item_buf);
01512     if (item->null_value)
01513       return 1;         // This must be true
01514     field_val= field->val_decimal(&field_buf);
01515     return !class_decimal_cmp(item_val, field_val);
01516   }
01517 
01518   double result= item->val_real();
01519   if (item->null_value)
01520     return 1;
01521 
01522   return result == field->val_real();
01523 }
01524 
01548 static Field *create_tmp_field_from_item(Session *,
01549                                          Item *item, Table *table,
01550                                          Item ***copy_func, bool modify_item,
01551                                          uint32_t convert_blob_length)
01552 {
01553   bool maybe_null= item->maybe_null;
01554   Field *new_field= NULL;
01555 
01556   switch (item->result_type()) {
01557   case REAL_RESULT:
01558     new_field= new Field_double(item->max_length, maybe_null,
01559                                 item->name, item->decimals, true);
01560     break;
01561 
01562   case INT_RESULT:
01563     /*
01564       Select an integer type with the minimal fit precision.
01565       MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
01566       Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into
01567       Int32 -> make them field::Int64.
01568     */
01569     if (item->unsigned_flag)
01570     {
01571       new_field= new field::Size(item->max_length, maybe_null, item->name, item->unsigned_flag);
01572     }
01573     else if (item->max_length >= MY_INT32_NUM_DECIMAL_DIGITS - 1)
01574     {
01575       new_field= new field::Int64(item->max_length, maybe_null, item->name, item->unsigned_flag);
01576     }
01577     else
01578     {
01579       new_field= new field::Int32(item->max_length, maybe_null, item->name, item->unsigned_flag);
01580     }
01581 
01582     break;
01583 
01584   case STRING_RESULT:
01585     assert(item->collation.collation);
01586 
01587     /*
01588       DATE/TIME fields have STRING_RESULT result type.
01589       To preserve type they needed to be handled separately.
01590     */
01591     if (field::isDateTime(item->field_type()))
01592     {
01593       new_field= item->tmp_table_field_from_field_type(table, 1);
01594       /*
01595         Make sure that the blob fits into a Field_varstring which has
01596         2-byte lenght.
01597       */
01598     }
01599     else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
01600              convert_blob_length <= Field_varstring::MAX_SIZE &&
01601              convert_blob_length)
01602     {
01603       table->setVariableWidth();
01604       new_field= new Field_varstring(convert_blob_length, maybe_null,
01605                                      item->name, item->collation.collation);
01606     }
01607     else
01608     {
01609       new_field= item->make_string_field(table);
01610     }
01611     new_field->set_derivation(item->collation.derivation);
01612     break;
01613 
01614   case DECIMAL_RESULT:
01615     {
01616       uint8_t dec= item->decimals;
01617       uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
01618       uint32_t len= item->max_length;
01619 
01620       /*
01621         Trying to put too many digits overall in a DECIMAL(prec,dec)
01622         will always throw a warning. We must limit dec to
01623         DECIMAL_MAX_SCALE however to prevent an assert() later.
01624       */
01625 
01626       if (dec > 0)
01627       {
01628         signed int overflow;
01629 
01630         dec= min(dec, (uint8_t)DECIMAL_MAX_SCALE);
01631 
01632         /*
01633           If the value still overflows the field with the corrected dec,
01634           we'll throw out decimals rather than integers. This is still
01635           bad and of course throws a truncation warning.
01636           +1: for decimal point
01637         */
01638 
01639         overflow= class_decimal_precision_to_length(intg + dec, dec,
01640                                                  item->unsigned_flag) - len;
01641 
01642         if (overflow > 0)
01643           dec= max(0, dec - overflow);            // too long, discard fract
01644         else
01645           len-= item->decimals - dec;             // corrected value fits
01646       }
01647 
01648       new_field= new Field_decimal(len,
01649                                    maybe_null,
01650                                    item->name,
01651                                    dec,
01652                                    item->unsigned_flag);
01653       break;
01654     }
01655 
01656   case ROW_RESULT:
01657     // This case should never be choosen
01658     assert(0);
01659     abort();
01660   }
01661 
01662   if (new_field)
01663     new_field->init(table);
01664 
01665   if (copy_func && item->is_result_field())
01666     *((*copy_func)++) = item;     // Save for copy_funcs
01667 
01668   if (modify_item)
01669     item->set_result_field(new_field);
01670 
01671   if (item->type() == Item::NULL_ITEM)
01672     new_field->is_created_from_null_item= true;
01673 
01674   return new_field;
01675 }
01676 
01677 Field *create_tmp_field(Session *session,
01678                         Table *table,
01679                         Item *item,
01680                         Item::Type type,
01681                         Item ***copy_func,
01682                         Field **from_field,
01683                         Field **default_field,
01684                         bool group,
01685                         bool modify_item,
01686                         bool make_copy_field,
01687                         uint32_t convert_blob_length)
01688 {
01689   Field *result;
01690   Item::Type orig_type= type;
01691   Item *orig_item= 0;
01692 
01693   if (type != Item::FIELD_ITEM &&
01694       item->real_item()->type() == Item::FIELD_ITEM)
01695   {
01696     orig_item= item;
01697     item= item->real_item();
01698     type= Item::FIELD_ITEM;
01699   }
01700 
01701   switch (type) {
01702   case Item::SUM_FUNC_ITEM:
01703   {
01704     Item_sum *item_sum=(Item_sum*) item;
01705     result= item_sum->create_tmp_field(group, table, convert_blob_length);
01706     if (!result)
01707       my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
01708     return result;
01709   }
01710   case Item::FIELD_ITEM:
01711   case Item::DEFAULT_VALUE_ITEM:
01712   {
01713     Item_field *field= (Item_field*) item;
01714     bool orig_modify= modify_item;
01715     if (orig_type == Item::REF_ITEM)
01716       modify_item= 0;
01717     /*
01718       If item have to be able to store NULLs but underlaid field can't do it,
01719       create_tmp_field_from_field() can't be used for tmp field creation.
01720     */
01721     if (field->maybe_null && !field->field->maybe_null())
01722     {
01723       result= create_tmp_field_from_item(session, item, table, NULL,
01724                                          modify_item, convert_blob_length);
01725       *from_field= field->field;
01726       if (result && modify_item)
01727         field->result_field= result;
01728     }
01729     else
01730     {
01731       result= create_tmp_field_from_field(session, (*from_field= field->field),
01732                                           orig_item ? orig_item->name :
01733                                           item->name,
01734                                           table,
01735                                           modify_item ? field :
01736                                           NULL,
01737                                           convert_blob_length);
01738     }
01739     if (orig_type == Item::REF_ITEM && orig_modify)
01740       ((Item_ref*)orig_item)->set_result_field(result);
01741     if (field->field->eq_def(result))
01742       *default_field= field->field;
01743     return result;
01744   }
01745   /* Fall through */
01746   case Item::FUNC_ITEM:
01747     /* Fall through */
01748   case Item::COND_ITEM:
01749   case Item::FIELD_AVG_ITEM:
01750   case Item::FIELD_STD_ITEM:
01751   case Item::SUBSELECT_ITEM:
01752     /* The following can only happen with 'CREATE TABLE ... SELECT' */
01753   case Item::PROC_ITEM:
01754   case Item::INT_ITEM:
01755   case Item::REAL_ITEM:
01756   case Item::DECIMAL_ITEM:
01757   case Item::STRING_ITEM:
01758   case Item::REF_ITEM:
01759   case Item::NULL_ITEM:
01760   case Item::VARBIN_ITEM:
01761     if (make_copy_field)
01762     {
01763       assert(((Item_result_field*)item)->result_field);
01764       *from_field= ((Item_result_field*)item)->result_field;
01765     }
01766     return create_tmp_field_from_item(session, item, table,
01767                                       (make_copy_field ? 0 : copy_func),
01768                                        modify_item, convert_blob_length);
01769   case Item::TYPE_HOLDER:
01770     result= ((Item_type_holder *)item)->make_field_by_type(table);
01771     result->set_derivation(item->collation.derivation);
01772     return result;
01773   default:          // Dosen't have to be stored
01774     return NULL;
01775   }
01776 }
01777 
01778 std::ostream& operator<<(std::ostream& output, const Item &item)
01779 {
01780   switch (item.type())
01781   {
01782   case drizzled::Item::SUBSELECT_ITEM :
01783   case drizzled::Item::FIELD_ITEM :
01784   case drizzled::Item::SUM_FUNC_ITEM :
01785   case drizzled::Item::STRING_ITEM :
01786   case drizzled::Item::INT_ITEM :
01787   case drizzled::Item::REAL_ITEM :
01788   case drizzled::Item::NULL_ITEM :
01789   case drizzled::Item::VARBIN_ITEM :
01790   case drizzled::Item::COPY_STR_ITEM :
01791   case drizzled::Item::FIELD_AVG_ITEM :
01792   case drizzled::Item::DEFAULT_VALUE_ITEM :
01793   case drizzled::Item::PROC_ITEM :
01794   case drizzled::Item::COND_ITEM :
01795   case drizzled::Item::REF_ITEM :
01796   case drizzled::Item::FIELD_STD_ITEM :
01797   case drizzled::Item::FIELD_VARIANCE_ITEM :
01798   case drizzled::Item::INSERT_VALUE_ITEM :
01799   case drizzled::Item::ROW_ITEM:
01800   case drizzled::Item::CACHE_ITEM :
01801   case drizzled::Item::TYPE_HOLDER :
01802   case drizzled::Item::PARAM_ITEM :
01803   case drizzled::Item::DECIMAL_ITEM :
01804   case drizzled::Item::FUNC_ITEM :
01805   case drizzled::Item::BOOLEAN_ITEM :
01806     {
01807       output << "Item:(";
01808       output <<  item.full_name();
01809       output << ", ";
01810       output << drizzled::display::type(item.type());
01811       output << ")";
01812     }
01813     break;
01814   }
01815 
01816   return output;  // for multiple << operators.
01817 }
01818 
01819 } /* namespace drizzled */