1
/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
3
This program is free software; you can redistribute it and/or modify
4
it under the terms of the GNU General Public License as published by
5
the Free Software Foundation; version 2 of the License.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
17
#ifdef USE_PRAGMA_IMPLEMENTATION
18
#pragma implementation // gcc: Class implementation
20
#include "mysql_priv.h"
24
#include "sp_rcontext.h"
26
#include "sql_trigger.h"
27
#include "sql_select.h"
29
const String my_null_string("NULL", 4, default_charset_info);
31
/****************************************************************************/
33
/* Hybrid_type_traits {_real} */
35
void Hybrid_type_traits::fix_length_and_dec(Item *item, Item *arg) const
37
item->decimals= NOT_FIXED_DEC;
38
item->max_length= item->float_length(arg->decimals);
41
static const Hybrid_type_traits real_traits_instance;
43
const Hybrid_type_traits *Hybrid_type_traits::instance()
45
return &real_traits_instance;
50
Hybrid_type_traits::val_decimal(Hybrid_type *val, my_decimal *to) const
52
double2my_decimal(E_DEC_FATAL_ERROR, val->real, val->dec_buf);
58
Hybrid_type_traits::val_str(Hybrid_type *val, String *to, uint8 decimals) const
60
to->set_real(val->real, decimals, &my_charset_bin);
64
/* Hybrid_type_traits_decimal */
65
static const Hybrid_type_traits_decimal decimal_traits_instance;
67
const Hybrid_type_traits_decimal *Hybrid_type_traits_decimal::instance()
69
return &decimal_traits_instance;
74
Hybrid_type_traits_decimal::fix_length_and_dec(Item *item, Item *arg) const
76
item->decimals= arg->decimals;
77
item->max_length= min(arg->max_length + DECIMAL_LONGLONG_DIGITS,
78
DECIMAL_MAX_STR_LENGTH);
82
void Hybrid_type_traits_decimal::set_zero(Hybrid_type *val) const
84
my_decimal_set_zero(&val->dec_buf[0]);
85
val->used_dec_buf_no= 0;
89
void Hybrid_type_traits_decimal::add(Hybrid_type *val, Field *f) const
91
my_decimal_add(E_DEC_FATAL_ERROR,
92
&val->dec_buf[val->used_dec_buf_no ^ 1],
93
&val->dec_buf[val->used_dec_buf_no],
94
f->val_decimal(&val->dec_buf[2]));
95
val->used_dec_buf_no^= 1;
101
what is '4' for scale?
103
void Hybrid_type_traits_decimal::div(Hybrid_type *val, ulonglong u) const
105
int2my_decimal(E_DEC_FATAL_ERROR, u, TRUE, &val->dec_buf[2]);
106
/* XXX: what is '4' for scale? */
107
my_decimal_div(E_DEC_FATAL_ERROR,
108
&val->dec_buf[val->used_dec_buf_no ^ 1],
109
&val->dec_buf[val->used_dec_buf_no],
110
&val->dec_buf[2], 4);
111
val->used_dec_buf_no^= 1;
116
Hybrid_type_traits_decimal::val_int(Hybrid_type *val, bool unsigned_flag) const
119
my_decimal2int(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
120
unsigned_flag, &result);
126
Hybrid_type_traits_decimal::val_real(Hybrid_type *val) const
128
my_decimal2double(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
135
Hybrid_type_traits_decimal::val_str(Hybrid_type *val, String *to,
136
uint8 decimals) const
138
my_decimal_round(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
139
decimals, FALSE, &val->dec_buf[2]);
140
my_decimal2string(E_DEC_FATAL_ERROR, &val->dec_buf[2], 0, 0, 0, to);
144
/* Hybrid_type_traits_integer */
145
static const Hybrid_type_traits_integer integer_traits_instance;
147
const Hybrid_type_traits_integer *Hybrid_type_traits_integer::instance()
149
return &integer_traits_instance;
153
Hybrid_type_traits_integer::fix_length_and_dec(Item *item, Item *arg) const
156
item->max_length= MY_INT64_NUM_DECIMAL_DIGITS;
157
item->unsigned_flag= 0;
160
/*****************************************************************************
162
*****************************************************************************/
165
Init all special items.
170
item_user_lock_init();
177
Make this functions class dependent
180
bool Item::val_bool()
182
switch(result_type()) {
184
return val_int() != 0;
187
my_decimal decimal_value;
188
my_decimal *val= val_decimal(&decimal_value);
190
return !my_decimal_is_zero(val);
195
return val_real() != 0.0;
199
return 0; // Wrong (but safe)
204
String *Item::val_string_from_real(String *str)
206
double nr= val_real();
208
return 0; /* purecov: inspected */
209
str->set_real(nr,decimals, &my_charset_bin);
214
String *Item::val_string_from_int(String *str)
216
longlong nr= val_int();
219
str->set_int(nr, unsigned_flag, &my_charset_bin);
224
String *Item::val_string_from_decimal(String *str)
226
my_decimal dec_buf, *dec= val_decimal(&dec_buf);
229
my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
230
my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
235
my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
237
double nr= val_real();
240
double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
241
return (decimal_value);
245
my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
247
longlong nr= val_int();
250
int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
251
return decimal_value;
255
my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
259
if (!(res= val_str(&str_value)))
260
return 0; // NULL or EOM
262
end_ptr= (char*) res->ptr()+ res->length();
263
if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
264
res->ptr(), res->length(), res->charset(),
265
decimal_value) & E_DEC_BAD_NUM)
267
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
268
ER_TRUNCATED_WRONG_VALUE,
269
ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
272
return decimal_value;
276
my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value)
278
DBUG_ASSERT(fixed == 1);
280
if (get_date(<ime, TIME_FUZZY_DATE))
282
my_decimal_set_zero(decimal_value);
283
null_value= 1; // set NULL, stop processing
286
return date2my_decimal(<ime, decimal_value);
290
my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value)
292
DBUG_ASSERT(fixed == 1);
294
if (get_time(<ime))
296
my_decimal_set_zero(decimal_value);
299
return date2my_decimal(<ime, decimal_value);
303
double Item::val_real_from_decimal()
305
/* Note that fix_fields may not be called for Item_avg_field items */
307
my_decimal value_buff, *dec_val= val_decimal(&value_buff);
310
my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
315
longlong Item::val_int_from_decimal()
317
/* Note that fix_fields may not be called for Item_avg_field items */
319
my_decimal value, *dec_val= val_decimal(&value);
322
my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result);
326
int Item::save_time_in_field(Field *field)
329
if (get_time(<ime))
330
return set_field_to_null_with_conversions(field, 0);
331
field->set_notnull();
332
return field->store_time(<ime, MYSQL_TIMESTAMP_TIME);
336
int Item::save_date_in_field(Field *field)
339
if (get_date(<ime, TIME_FUZZY_DATE))
340
return set_field_to_null_with_conversions(field, 0);
341
field->set_notnull();
342
return field->store_time(<ime, MYSQL_TIMESTAMP_DATETIME);
347
Store the string value in field directly
350
Item::save_str_value_in_field()
351
field a pointer to field where to store
352
result the pointer to the string value to be stored
355
The method is used by Item_*::save_in_field implementations
356
when we don't need to calculate the value to store
357
See Item_string::save_in_field() implementation for example
360
Check if the Item is null and stores the NULL or the
361
result value in the field accordingly.
364
Nonzero value if error
367
int Item::save_str_value_in_field(Field *field, String *result)
370
return set_field_to_null(field);
371
field->set_notnull();
372
return field->store(result->ptr(), result->length(),
373
collation.collation);
378
rsize(0), name(0), orig_name(0), name_length(0), fixed(0),
379
is_autogenerated_name(TRUE),
380
collation(&my_charset_bin, DERIVATION_COERCIBLE)
383
maybe_null=null_value=with_sum_func=unsigned_flag=0;
384
decimals= 0; max_length= 0;
386
cmp_context= (Item_result)-1;
388
/* Put item in free list so that we can free all items at end */
389
THD *thd= current_thd;
390
next= thd->free_list;
391
thd->free_list= this;
393
Item constructor can be called during execution other then SQL_COM
394
command => we should check thd->lex->current_select on zero (thd->lex
395
can be uninitialised)
397
if (thd->lex->current_select)
399
enum_parsing_place place=
400
thd->lex->current_select->parsing_place;
401
if (place == SELECT_LIST ||
403
thd->lex->current_select->select_n_having_items++;
408
Constructor used by Item_field, Item_ref & aggregate (sum)
411
Used for duplicating lists in processing queries with temporary
414
Item::Item(THD *thd, Item *item):
416
str_value(item->str_value),
418
orig_name(item->orig_name),
419
max_length(item->max_length),
420
name_length(item->name_length),
421
marker(item->marker),
422
decimals(item->decimals),
423
maybe_null(item->maybe_null),
424
null_value(item->null_value),
425
unsigned_flag(item->unsigned_flag),
426
with_sum_func(item->with_sum_func),
428
is_autogenerated_name(item->is_autogenerated_name),
429
collation(item->collation),
430
with_subselect(item->with_subselect),
431
cmp_context(item->cmp_context)
433
next= thd->free_list; // Put in free list
434
thd->free_list= this;
438
uint Item::decimal_precision() const
440
Item_result restype= result_type();
442
if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
445
my_decimal_length_to_precision(max_length, decimals, unsigned_flag);
446
return min(prec, DECIMAL_MAX_PRECISION);
448
return min(max_length, DECIMAL_MAX_PRECISION);
452
void Item::print_item_w_name(String *str, enum_query_type query_type)
454
print(str, query_type);
458
THD *thd= current_thd;
459
str->append(STRING_WITH_LEN(" AS "));
460
append_identifier(thd, str, name, (uint) strlen(name));
467
DBUG_ENTER("Item::cleanup");
477
cleanup() item if it is 'fixed'.
479
@param arg a dummy parameter, is not used here
482
bool Item::cleanup_processor(uchar *arg)
491
rename item (used for views, cleanup() return original name).
493
@param new_name new name of item;
496
void Item::rename(char *new_name)
499
we can compare pointers to names here, because if name was not changed,
502
if (!orig_name && new_name != name)
509
Traverse item tree possibly transforming it (replacing items).
511
This function is designed to ease transformation of Item trees.
512
Re-execution note: every such transformation is registered for
513
rollback by THD::change_item_tree() and is rolled back at the end
514
of execution by THD::rollback_item_tree_changes().
517
- this function can not be used at prepared statement prepare
518
(in particular, in fix_fields!), as only permanent
519
transformation of Item trees are allowed at prepare.
520
- the transformer function shall allocate new Items in execution
521
memory root (thd->mem_root) and not anywhere else: allocated
522
items will be gone in the end of execution.
524
If you don't need to transform an item tree, but only traverse
525
it, please use Item::walk() instead.
528
@param transformer functor that performs transformation of a subtree
529
@param arg opaque argument passed to the functor
532
Returns pointer to the new subtree root. THD::change_item_tree()
533
should be called for it if transformation took place, i.e. if a
534
pointer to newly allocated item is returned.
537
Item* Item::transform(Item_transformer transformer, uchar *arg)
539
DBUG_ASSERT(!current_thd->is_stmt_prepare());
541
return (this->*transformer)(arg);
545
Item_ident::Item_ident(Name_resolution_context *context_arg,
546
const char *db_name_arg,const char *table_name_arg,
547
const char *field_name_arg)
548
:orig_db_name(db_name_arg), orig_table_name(table_name_arg),
549
orig_field_name(field_name_arg), context(context_arg),
550
db_name(db_name_arg), table_name(table_name_arg),
551
field_name(field_name_arg),
552
alias_name_used(FALSE), cached_field_index(NO_CACHED_FIELD_INDEX),
553
cached_table(0), depended_from(0)
555
name = (char*) field_name_arg;
560
Constructor used by Item_field & Item_*_ref (see Item comment)
563
Item_ident::Item_ident(THD *thd, Item_ident *item)
565
orig_db_name(item->orig_db_name),
566
orig_table_name(item->orig_table_name),
567
orig_field_name(item->orig_field_name),
568
context(item->context),
569
db_name(item->db_name),
570
table_name(item->table_name),
571
field_name(item->field_name),
572
alias_name_used(item->alias_name_used),
573
cached_field_index(item->cached_field_index),
574
cached_table(item->cached_table),
575
depended_from(item->depended_from)
578
void Item_ident::cleanup()
580
DBUG_ENTER("Item_ident::cleanup");
581
#ifdef CANT_BE_USED_AS_MEMORY_IS_FREED
582
db_name ? db_name : "(null)",
583
orig_db_name ? orig_db_name : "(null)",
584
table_name ? table_name : "(null)",
585
orig_table_name ? orig_table_name : "(null)",
586
field_name ? field_name : "(null)",
587
orig_field_name ? orig_field_name : "(null)"));
590
db_name= orig_db_name;
591
table_name= orig_table_name;
592
field_name= orig_field_name;
597
bool Item_ident::remove_dependence_processor(uchar * arg)
599
DBUG_ENTER("Item_ident::remove_dependence_processor");
600
if (depended_from == (st_select_lex *) arg)
602
context= &((st_select_lex *) arg)->context;
608
Store the pointer to this item field into a list if not already there.
610
The method is used by Item::walk to collect all unique Item_field objects
611
from a tree of Items into a set of items represented as a list.
613
Item_cond::walk() and Item_func::walk() stop the evaluation of the
614
processor function for its arguments once the processor returns
615
true.Therefore in order to force this method being called for all item
616
arguments in a condition the method must return false.
618
@param arg pointer to a List<Item_field>
621
FALSE to force the evaluation of collect_item_field_processor
622
for the subsequent items.
625
bool Item_field::collect_item_field_processor(uchar *arg)
627
DBUG_ENTER("Item_field::collect_item_field_processor");
628
DBUG_PRINT("info", ("%s", field->field_name ? field->field_name : "noname"));
629
List<Item_field> *item_list= (List<Item_field>*) arg;
630
List_iterator<Item_field> item_list_it(*item_list);
631
Item_field *curr_item;
632
while ((curr_item= item_list_it++))
634
if (curr_item->eq(this, 1))
635
DBUG_RETURN(FALSE); /* Already in the set. */
637
item_list->push_back(this);
643
Check if an Item_field references some field from a list of fields.
645
Check whether the Item_field represented by 'this' references any
646
of the fields in the keyparts passed via 'arg'. Used with the
647
method Item::walk() to test whether any keypart in a sequence of
648
keyparts is referenced in an expression.
650
@param arg Field being compared, arg must be of type Field
653
TRUE if 'this' references the field 'arg'
658
bool Item_field::find_item_in_field_list_processor(uchar *arg)
660
KEY_PART_INFO *first_non_group_part= *((KEY_PART_INFO **) arg);
661
KEY_PART_INFO *last_part= *(((KEY_PART_INFO **) arg) + 1);
662
KEY_PART_INFO *cur_part;
664
for (cur_part= first_non_group_part; cur_part != last_part; cur_part++)
666
if (field->eq(cur_part->field))
674
Mark field in read_map
677
This is used by filesort to register used fields in a a temporary
678
column read set or to register used fields in a view
681
bool Item_field::register_field_in_read_map(uchar *arg)
683
TABLE *table= (TABLE *) arg;
684
if (field->table == table || !table)
685
bitmap_set_bit(field->table->read_set, field->field_index);
690
bool Item::check_cols(uint c)
694
my_error(ER_OPERAND_COLUMNS, MYF(0), c);
701
void Item::set_name(const char *str, uint length, CHARSET_INFO *cs)
705
/* Empty string, used by AS or internal function like last_insert_id() */
712
uint orig_len= length;
714
This will probably need a better implementation in the future:
715
a function in CHARSET_INFO structure.
717
while (length && !my_isgraph(cs,*str))
718
{ // Fix problem with yacc
722
if (orig_len != length && !is_autogenerated_name)
725
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
726
ER_NAME_BECOMES_EMPTY, ER(ER_NAME_BECOMES_EMPTY),
727
str + length - orig_len);
729
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
730
ER_REMOVED_SPACES, ER(ER_REMOVED_SPACES),
731
str + length - orig_len);
734
if (!my_charset_same(cs, system_charset_info))
737
name= sql_strmake_with_convert(str, name_length= length, cs,
738
MAX_ALIAS_NAME, system_charset_info,
742
name= sql_strmake(str, (name_length= min(length,MAX_ALIAS_NAME)));
748
This function is called when:
749
- Comparing items in the WHERE clause (when doing where optimization)
750
- When trying to find an ORDER BY/GROUP BY item in the SELECT part
753
bool Item::eq(const Item *item, bool binary_cmp) const
756
Note, that this is never TRUE if item is a Item_param:
757
for all basic constants we have special checks, and Item_param's
758
type() can be only among basic constant types.
760
return type() == item->type() && name && item->name &&
761
!my_strcasecmp(system_charset_info,name,item->name);
765
Item *Item::safe_charset_converter(CHARSET_INFO *tocs)
767
Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1);
768
return conv->safe ? conv : NULL;
774
Created mostly for mysql_prepare_table(). Important
775
when a string ENUM/SET column is described with a numeric default value:
777
CREATE TABLE t1(a SET('a') DEFAULT 1);
779
We cannot use generic Item::safe_charset_converter(), because
780
the latter returns a non-fixed Item, so val_str() crashes afterwards.
781
Override Item_num method, to return a fixed item.
783
Item *Item_num::safe_charset_converter(CHARSET_INFO *tocs)
787
String *s, tmp(buf, sizeof(buf), &my_charset_bin);
789
if ((conv= new Item_string(s->ptr(), s->length(), s->charset())))
791
conv->str_value.copy();
792
conv->str_value.mark_as_const();
798
Item *Item_static_float_func::safe_charset_converter(CHARSET_INFO *tocs)
802
String *s, tmp(buf, sizeof(buf), &my_charset_bin);
804
if ((conv= new Item_static_string_func(func_name, s->ptr(), s->length(),
807
conv->str_value.copy();
808
conv->str_value.mark_as_const();
814
Item *Item_string::safe_charset_converter(CHARSET_INFO *tocs)
819
String tmp, cstr, *ostr= val_str(&tmp);
820
cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
821
if (conv_errors || !(conv= new Item_string(cstr.ptr(), cstr.length(),
823
collation.derivation)))
826
Safe conversion is not possible (or EOM).
827
We could not convert a string into the requested character set
828
without data loss. The target charset does not cover all the
829
characters from the string. Operation cannot be done correctly.
833
if (!(ptr= current_thd->strmake(cstr.ptr(), cstr.length())))
835
conv->str_value.set(ptr, cstr.length(), cstr.charset());
836
/* Ensure that no one is going to change the result string */
837
conv->str_value.mark_as_const();
842
Item *Item_param::safe_charset_converter(CHARSET_INFO *tocs)
847
String *ostr= val_str(&cnvstr);
848
cnvitem->str_value.copy(ostr->ptr(), ostr->length(),
849
ostr->charset(), tocs, &cnv_errors);
852
cnvitem->str_value.mark_as_const();
853
cnvitem->max_length= cnvitem->str_value.numchars() * tocs->mbmaxlen;
860
Item *Item_static_string_func::safe_charset_converter(CHARSET_INFO *tocs)
864
String tmp, cstr, *ostr= val_str(&tmp);
865
cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
867
!(conv= new Item_static_string_func(func_name,
868
cstr.ptr(), cstr.length(),
870
collation.derivation)))
873
Safe conversion is not possible (or EOM).
874
We could not convert a string into the requested character set
875
without data loss. The target charset does not cover all the
876
characters from the string. Operation cannot be done correctly.
880
conv->str_value.copy();
881
/* Ensure that no one is going to change the result string */
882
conv->str_value.mark_as_const();
887
bool Item_string::eq(const Item *item, bool binary_cmp) const
889
if (type() == item->type() && item->basic_const_item())
892
return !stringcmp(&str_value, &item->str_value);
893
return (collation.collation == item->collation.collation &&
894
!sortcmp(&str_value, &item->str_value, collation.collation));
901
Get the value of the function as a MYSQL_TIME structure.
902
As a extra convenience the time structure is reset on error!
905
bool Item::get_date(MYSQL_TIME *ltime,uint fuzzydate)
907
if (result_type() == STRING_RESULT)
910
String tmp(buff,sizeof(buff), &my_charset_bin),*res;
911
if (!(res=val_str(&tmp)) ||
912
str_to_datetime_with_warn(res->ptr(), res->length(),
913
ltime, fuzzydate) <= MYSQL_TIMESTAMP_ERROR)
918
longlong value= val_int();
920
if (number_to_datetime(value, ltime, fuzzydate, &was_cut) == LL(-1))
923
end= longlong10_to_str(value, buff, -10);
924
make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
925
buff, (int) (end-buff), MYSQL_TIMESTAMP_NONE,
933
bzero((char*) ltime,sizeof(*ltime));
938
Get time of first argument.\
940
As a extra convenience the time structure is reset on error!
943
bool Item::get_time(MYSQL_TIME *ltime)
946
String tmp(buff,sizeof(buff),&my_charset_bin),*res;
947
if (!(res=val_str(&tmp)) ||
948
str_to_time_with_warn(res->ptr(), res->length(), ltime))
950
bzero((char*) ltime,sizeof(*ltime));
956
CHARSET_INFO *Item::default_charset()
958
return current_thd->variables.collation_connection;
963
Save value in field, but don't give any warnings
966
This is used to temporary store and retrieve a value in a column,
967
for example in opt_range to adjust the key value to fit the column.
970
int Item::save_in_field_no_warnings(Field *field, bool no_conversions)
973
TABLE *table= field->table;
974
THD *thd= table->in_use;
975
enum_check_fields tmp= thd->count_cuted_fields;
976
my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
977
ulong sql_mode= thd->variables.sql_mode;
978
thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
979
thd->count_cuted_fields= CHECK_FIELD_IGNORE;
980
res= save_in_field(field, no_conversions);
981
thd->count_cuted_fields= tmp;
982
dbug_tmp_restore_column_map(table->write_set, old_map);
983
thd->variables.sql_mode= sql_mode;
988
/*****************************************************************************
989
Item_sp_variable methods
990
*****************************************************************************/
992
Item_sp_variable::Item_sp_variable(char *sp_var_name_str,
993
uint sp_var_name_length)
999
m_name.str= sp_var_name_str;
1000
m_name.length= sp_var_name_length;
1004
bool Item_sp_variable::fix_fields(THD *thd, Item **)
1008
m_thd= thd; /* NOTE: this must be set before any this_xxx() */
1011
DBUG_ASSERT(it->fixed);
1013
max_length= it->max_length;
1014
decimals= it->decimals;
1015
unsigned_flag= it->unsigned_flag;
1017
collation.set(it->collation.collation, it->collation.derivation);
1023
double Item_sp_variable::val_real()
1026
Item *it= this_item();
1027
double ret= it->val_real();
1028
null_value= it->null_value;
1033
longlong Item_sp_variable::val_int()
1036
Item *it= this_item();
1037
longlong ret= it->val_int();
1038
null_value= it->null_value;
1043
String *Item_sp_variable::val_str(String *sp)
1046
Item *it= this_item();
1047
String *res= it->val_str(sp);
1049
null_value= it->null_value;
1055
This way we mark returned value of val_str as const,
1056
so that various functions (e.g. CONCAT) won't try to
1057
modify the value of the Item. Analogous mechanism is
1058
implemented for Item_param.
1059
Without this trick Item_splocal could be changed as a
1060
side-effect of expression computation. Here is an example
1061
of what happens without it: suppose x is varchar local
1062
variable in a SP with initial value 'ab' Then
1063
select concat(x,'c');
1064
would change x's value to 'abc', as Item_func_concat::val_str()
1065
would use x's internal buffer to compute the result.
1066
This is intended behaviour of Item_func_concat. Comments to
1067
Item_param class contain some more details on the topic.
1070
if (res != &str_value)
1071
str_value.set(res->ptr(), res->length(), res->charset());
1073
res->mark_as_const();
1079
my_decimal *Item_sp_variable::val_decimal(my_decimal *decimal_value)
1082
Item *it= this_item();
1083
my_decimal *val= it->val_decimal(decimal_value);
1084
null_value= it->null_value;
1089
bool Item_sp_variable::is_null()
1091
return this_item()->is_null();
1095
/*****************************************************************************
1096
Item_splocal methods
1097
*****************************************************************************/
1099
Item_splocal::Item_splocal(const LEX_STRING &sp_var_name,
1101
enum_field_types sp_var_type,
1102
uint pos_in_q, uint len_in_q)
1103
:Item_sp_variable(sp_var_name.str, sp_var_name.length),
1104
m_var_idx(sp_var_idx), pos_in_query(pos_in_q), len_in_query(len_in_q)
1108
m_type= sp_map_item_type(sp_var_type);
1109
m_field_type= sp_var_type;
1110
m_result_type= sp_map_result_type(sp_var_type);
1115
Item_splocal::this_item()
1117
DBUG_ASSERT(m_sp == m_thd->spcont->sp);
1119
return m_thd->spcont->get_item(m_var_idx);
1123
Item_splocal::this_item() const
1125
DBUG_ASSERT(m_sp == m_thd->spcont->sp);
1127
return m_thd->spcont->get_item(m_var_idx);
1132
Item_splocal::this_item_addr(THD *thd, Item **)
1134
DBUG_ASSERT(m_sp == thd->spcont->sp);
1136
return thd->spcont->get_item_addr(m_var_idx);
1140
void Item_splocal::print(String *str, enum_query_type)
1142
str->reserve(m_name.length+8);
1143
str->append(m_name.str, m_name.length);
1145
str->qs_append(m_var_idx);
1149
bool Item_splocal::set_value(THD *thd, sp_rcontext *ctx, Item **it)
1151
return ctx->set_variable(thd, get_var_idx(), it);
1155
/*****************************************************************************
1156
Item_case_expr methods
1157
*****************************************************************************/
1159
Item_case_expr::Item_case_expr(uint case_expr_id)
1160
:Item_sp_variable( C_STRING_WITH_LEN("case_expr")),
1161
m_case_expr_id(case_expr_id)
1167
Item_case_expr::this_item()
1169
DBUG_ASSERT(m_sp == m_thd->spcont->sp);
1171
return m_thd->spcont->get_case_expr(m_case_expr_id);
1177
Item_case_expr::this_item() const
1179
DBUG_ASSERT(m_sp == m_thd->spcont->sp);
1181
return m_thd->spcont->get_case_expr(m_case_expr_id);
1186
Item_case_expr::this_item_addr(THD *thd, Item **)
1188
DBUG_ASSERT(m_sp == thd->spcont->sp);
1190
return thd->spcont->get_case_expr_addr(m_case_expr_id);
1194
void Item_case_expr::print(String *str, enum_query_type)
1196
if (str->reserve(MAX_INT_WIDTH + sizeof("case_expr@")))
1197
return; /* purecov: inspected */
1198
VOID(str->append(STRING_WITH_LEN("case_expr@")));
1199
str->qs_append(m_case_expr_id);
1203
/*****************************************************************************
1204
Item_name_const methods
1205
*****************************************************************************/
1207
double Item_name_const::val_real()
1210
double ret= value_item->val_real();
1211
null_value= value_item->null_value;
1216
longlong Item_name_const::val_int()
1219
longlong ret= value_item->val_int();
1220
null_value= value_item->null_value;
1225
String *Item_name_const::val_str(String *sp)
1228
String *ret= value_item->val_str(sp);
1229
null_value= value_item->null_value;
1234
my_decimal *Item_name_const::val_decimal(my_decimal *decimal_value)
1237
my_decimal *val= value_item->val_decimal(decimal_value);
1238
null_value= value_item->null_value;
1243
bool Item_name_const::is_null()
1245
return value_item->is_null();
1249
Item_name_const::Item_name_const(Item *name_arg, Item *val):
1250
value_item(val), name_item(name_arg)
1252
if (!(valid_args= name_item->basic_const_item() &&
1253
(value_item->basic_const_item() ||
1254
((value_item->type() == FUNC_ITEM) &&
1255
((((Item_func *) value_item)->functype() ==
1256
Item_func::COLLATE_FUNC) ||
1257
((((Item_func *) value_item)->functype() ==
1258
Item_func::NEG_FUNC) &&
1259
(((Item_func *) value_item)->key_item()->type() !=
1261
my_error(ER_WRONG_ARGUMENTS, MYF(0), "NAME_CONST");
1262
Item::maybe_null= TRUE;
1266
Item::Type Item_name_const::type() const
1270
1. one can try to create the Item_name_const passing non-constant
1271
arguments, although it's incorrect and
1272
2. the type() method can be called before the fix_fields() to get
1273
type information for a further type cast, e.g.
1274
if (item->type() == FIELD_ITEM)
1275
((Item_field *) item)->...
1276
we return NULL_ITEM in the case to avoid wrong casting.
1278
valid_args guarantees value_item->basic_const_item(); if type is
1279
FUNC_ITEM, then we have a fudged item_func_neg() on our hands
1280
and return the underlying type.
1281
For Item_func_set_collation()
1282
e.g. NAME_CONST('name', 'value' COLLATE collation) we return its
1283
'value' argument type.
1287
Item::Type value_type= value_item->type();
1288
if (value_type == FUNC_ITEM)
1291
The second argument of NAME_CONST('name', 'value') must be
1292
a simple constant item or a NEG_FUNC/COLLATE_FUNC.
1294
DBUG_ASSERT(((Item_func *) value_item)->functype() ==
1295
Item_func::NEG_FUNC ||
1296
((Item_func *) value_item)->functype() ==
1297
Item_func::COLLATE_FUNC);
1298
return ((Item_func *) value_item)->key_item()->type();
1304
bool Item_name_const::fix_fields(THD *thd, Item **ref)
1308
String s(buf, sizeof(buf), &my_charset_bin);
1311
if (value_item->fix_fields(thd, &value_item) ||
1312
name_item->fix_fields(thd, &name_item) ||
1313
!value_item->const_item() ||
1314
!name_item->const_item() ||
1315
!(item_name= name_item->val_str(&s))) // Can't have a NULL name
1317
my_error(ER_RESERVED_SYNTAX, MYF(0), "NAME_CONST");
1320
if (is_autogenerated_name)
1322
set_name(item_name->ptr(), (uint) item_name->length(), system_charset_info);
1324
collation.set(value_item->collation.collation, DERIVATION_IMPLICIT);
1325
max_length= value_item->max_length;
1326
decimals= value_item->decimals;
1332
void Item_name_const::print(String *str, enum_query_type query_type)
1334
str->append(STRING_WITH_LEN("NAME_CONST("));
1335
name_item->print(str, query_type);
1337
value_item->print(str, query_type);
1343
need a special class to adjust printing : references to aggregate functions
1344
must not be printed as refs because the aggregate functions that are added to
1345
the front of select list are not printed as well.
1347
class Item_aggregate_ref : public Item_ref
1350
Item_aggregate_ref(Name_resolution_context *context_arg, Item **item,
1351
const char *table_name_arg, const char *field_name_arg)
1352
:Item_ref(context_arg, item, table_name_arg, field_name_arg) {}
1354
virtual inline void print (String *str, enum_query_type query_type)
1357
(*ref)->print(str, query_type);
1359
Item_ident::print(str, query_type);
1361
virtual Ref_Type ref_type() { return AGGREGATE_REF; }
1366
Move SUM items out from item tree and replace with reference.
1368
@param thd Thread handler
1369
@param ref_pointer_array Pointer to array of reference fields
1370
@param fields All fields in select
1371
@param ref Pointer to item
1372
@param skip_registered <=> function be must skipped for registered
1376
This is from split_sum_func2() for items that should be split
1378
All found SUM items are added FIRST in the fields list and
1379
we replace the item with a reference.
1381
thd->fatal_error() may be called if we are out of memory
1384
void Item::split_sum_func2(THD *thd, Item **ref_pointer_array,
1385
List<Item> &fields, Item **ref,
1386
bool skip_registered)
1388
/* An item of type Item_sum is registered <=> ref_by != 0 */
1389
if (type() == SUM_FUNC_ITEM && skip_registered &&
1390
((Item_sum *) this)->ref_by)
1392
if ((type() != SUM_FUNC_ITEM && with_sum_func) ||
1393
(type() == FUNC_ITEM &&
1394
(((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC ||
1395
((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC)))
1397
/* Will split complicated items and ignore simple ones */
1398
split_sum_func(thd, ref_pointer_array, fields);
1400
else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) &&
1401
type() != SUBSELECT_ITEM &&
1402
(type() != REF_ITEM ||
1403
((Item_ref*)this)->ref_type() == Item_ref::VIEW_REF))
1406
Replace item with a reference so that we can easily calculate
1407
it (in case of sum functions) or copy it (in case of fields)
1409
The test above is to ensure we don't do a reference for things
1410
that are constants (PARAM_TABLE_BIT is in effect a constant)
1411
or already referenced (for example an item in HAVING)
1412
Exception is Item_direct_view_ref which we need to convert to
1413
Item_ref to allow fields from view being stored in tmp table.
1415
Item_aggregate_ref *item_ref;
1416
uint el= fields.elements;
1417
Item *real_itm= real_item();
1419
ref_pointer_array[el]= real_itm;
1420
if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context,
1421
ref_pointer_array + el, 0, name)))
1422
return; // fatal_error is set
1423
if (type() == SUM_FUNC_ITEM)
1424
item_ref->depended_from= ((Item_sum *) this)->depended_from();
1425
fields.push_front(real_itm);
1426
thd->change_item_tree(ref, item_ref);
1432
left_is_superset(DTCollation *left, DTCollation *right)
1434
/* Allow convert to Unicode */
1435
if (left->collation->state & MY_CS_UNICODE &&
1436
(left->derivation < right->derivation ||
1437
(left->derivation == right->derivation &&
1438
!(right->collation->state & MY_CS_UNICODE))))
1440
/* Allow convert from ASCII */
1441
if (right->repertoire == MY_REPERTOIRE_ASCII &&
1442
(left->derivation < right->derivation ||
1443
(left->derivation == right->derivation &&
1444
!(left->repertoire == MY_REPERTOIRE_ASCII))))
1446
/* Disallow conversion otherwise */
1451
Aggregate two collations together taking
1452
into account their coercibility (aka derivation):.
1454
0 == DERIVATION_EXPLICIT - an explicitly written COLLATE clause @n
1455
1 == DERIVATION_NONE - a mix of two different collations @n
1456
2 == DERIVATION_IMPLICIT - a column @n
1457
3 == DERIVATION_COERCIBLE - a string constant.
1459
The most important rules are:
1460
-# If collations are the same:
1461
chose this collation, and the strongest derivation.
1462
-# If collations are different:
1463
- Character sets may differ, but only if conversion without
1464
data loss is possible. The caller provides flags whether
1465
character set conversion attempts should be done. If no
1466
flags are substituted, then the character sets must be the same.
1467
Currently processed flags are:
1468
MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset
1469
MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
1470
- two EXPLICIT collations produce an error, e.g. this is wrong:
1471
CONCAT(expr1 collate latin1_swedish_ci, expr2 collate latin1_german_ci)
1472
- the side with smaller derivation value wins,
1473
i.e. a column is stronger than a string constant,
1474
an explicit COLLATE clause is stronger than a column.
1475
- if derivations are the same, we have DERIVATION_NONE,
1476
we'll wait for an explicit COLLATE clause which possibly can
1477
come from another argument later: for example, this is valid,
1478
but we don't know yet when collecting the first two arguments:
1480
CONCAT(latin1_swedish_ci_column,
1481
latin1_german1_ci_column,
1482
expr COLLATE latin1_german2_ci)
1486
bool DTCollation::aggregate(DTCollation &dt, uint flags)
1488
if (!my_charset_same(collation, dt.collation))
1491
We do allow to use binary strings (like BLOBS)
1492
together with character strings.
1493
Binaries have more precedence than a character
1494
string of the same derivation.
1496
if (collation == &my_charset_bin)
1498
if (derivation <= dt.derivation)
1505
else if (dt.collation == &my_charset_bin)
1507
if (dt.derivation <= derivation)
1512
else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
1513
left_is_superset(this, &dt))
1517
else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
1518
left_is_superset(&dt, this))
1522
else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
1523
derivation < dt.derivation &&
1524
dt.derivation >= DERIVATION_SYSCONST)
1528
else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
1529
dt.derivation < derivation &&
1530
derivation >= DERIVATION_SYSCONST)
1536
// Cannot apply conversion
1537
set(&my_charset_bin, DERIVATION_NONE,
1538
(dt.repertoire|repertoire));
1542
else if (derivation < dt.derivation)
1546
else if (dt.derivation < derivation)
1552
if (collation == dt.collation)
1558
if (derivation == DERIVATION_EXPLICIT)
1560
set(0, DERIVATION_NONE, 0);
1563
if (collation->state & MY_CS_BINSORT)
1565
if (dt.collation->state & MY_CS_BINSORT)
1570
CHARSET_INFO *bin= get_charset_by_csname(collation->csname,
1571
MY_CS_BINSORT,MYF(0));
1572
set(bin, DERIVATION_NONE);
1575
repertoire|= dt.repertoire;
1579
/******************************/
1581
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname)
1583
my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
1584
c1.collation->name,c1.derivation_name(),
1585
c2.collation->name,c2.derivation_name(),
1591
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, DTCollation &c3,
1594
my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0),
1595
c1.collation->name,c1.derivation_name(),
1596
c2.collation->name,c2.derivation_name(),
1597
c3.collation->name,c3.derivation_name(),
1603
void my_coll_agg_error(Item** args, uint count, const char *fname,
1607
my_coll_agg_error(args[0]->collation, args[item_sep]->collation, fname);
1608
else if (count == 3)
1609
my_coll_agg_error(args[0]->collation, args[item_sep]->collation,
1610
args[2*item_sep]->collation, fname);
1612
my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname);
1616
bool agg_item_collations(DTCollation &c, const char *fname,
1617
Item **av, uint count, uint flags, int item_sep)
1623
c.set(av[0]->collation);
1624
for (i= 1, arg= &av[item_sep]; i < count; i++, arg++)
1626
if (c.aggregate((*arg)->collation, flags))
1628
if (c.derivation == DERIVATION_NONE &&
1629
c.collation == &my_charset_bin)
1634
my_coll_agg_error(av, count, fname, item_sep);
1640
c.derivation != DERIVATION_EXPLICIT)
1642
my_coll_agg_error(av, count, fname, item_sep);
1646
if ((flags & MY_COLL_DISALLOW_NONE) &&
1647
c.derivation == DERIVATION_NONE)
1649
my_coll_agg_error(av, count, fname, item_sep);
1656
bool agg_item_collations_for_comparison(DTCollation &c, const char *fname,
1657
Item **av, uint count, uint flags)
1659
return (agg_item_collations(c, fname, av, count,
1660
flags | MY_COLL_DISALLOW_NONE, 1));
1664
bool agg_item_set_converter(DTCollation &coll, const char *fname,
1665
Item **args, uint nargs, uint flags, int item_sep)
1667
Item **arg, *safe_args[2]= {NULL, NULL};
1670
For better error reporting: save the first and the second argument.
1671
We need this only if the the number of args is 3 or 2:
1672
- for a longer argument list, "Illegal mix of collations"
1673
doesn't display each argument's characteristics.
1674
- if nargs is 1, then this error cannot happen.
1676
if (nargs >=2 && nargs <= 3)
1678
safe_args[0]= args[0];
1679
safe_args[1]= args[item_sep];
1682
THD *thd= current_thd;
1683
Query_arena *arena, backup;
1687
In case we're in statement prepare, create conversion item
1688
in its memory: it will be reused on each execute.
1690
arena= thd->is_stmt_prepare() ? thd->activate_stmt_arena_if_needed(&backup)
1693
for (i= 0, arg= args; i < nargs; i++, arg+= item_sep)
1696
uint32 dummy_offset;
1697
if (!String::needs_conversion(0, (*arg)->collation.collation,
1702
if (!(conv= (*arg)->safe_charset_converter(coll.collation)) &&
1703
((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII))
1704
conv= new Item_func_conv_charset(*arg, coll.collation, 1);
1708
if (nargs >=2 && nargs <= 3)
1710
/* restore the original arguments for better error message */
1711
args[0]= safe_args[0];
1712
args[item_sep]= safe_args[1];
1714
my_coll_agg_error(args, nargs, fname, item_sep);
1716
break; // we cannot return here, we need to restore "arena".
1718
if ((*arg)->type() == Item::FIELD_ITEM)
1719
((Item_field *)(*arg))->no_const_subst= 1;
1721
If in statement prepare, then we create a converter for two
1722
constant items, do it once and then reuse it.
1723
If we're in execution of a prepared statement, arena is NULL,
1724
and the conv was created in runtime memory. This can be
1725
the case only if the argument is a parameter marker ('?'),
1726
because for all true constants the charset converter has already
1727
been created in prepare. In this case register the change for
1730
if (thd->is_stmt_prepare())
1733
thd->change_item_tree(arg, conv);
1735
We do not check conv->fixed, because Item_func_conv_charset which can
1736
be return by safe_charset_converter can't be fixed at creation
1738
conv->fix_fields(thd, arg);
1741
thd->restore_active_arena(arena, &backup);
1747
Collect arguments' character sets together.
1748
We allow to apply automatic character set conversion in some cases.
1749
The conditions when conversion is possible are:
1750
- arguments A and B have different charsets
1751
- A wins according to coercibility rules
1752
(i.e. a column is stronger than a string constant,
1753
an explicit COLLATE clause is stronger than a column)
1754
- character set of A is either superset for character set of B,
1755
or B is a string constant which can be converted into the
1756
character set of A without data loss.
1758
If all of the above is true, then it's possible to convert
1759
B into the character set of A, and then compare according
1760
to the collation of A.
1762
For functions with more than two arguments:
1764
collect(A,B,C) ::= collect(collect(A,B),C)
1766
Since this function calls THD::change_item_tree() on the passed Item **
1767
pointers, it is necessary to pass the original Item **'s, not copies.
1768
Otherwise their values will not be properly restored (see BUG#20769).
1769
If the items are not consecutive (eg. args[2] and args[5]), use the
1770
item_sep argument, ie.
1772
agg_item_charsets(coll, fname, &args[2], 2, flags, 3)
1776
bool agg_item_charsets(DTCollation &coll, const char *fname,
1777
Item **args, uint nargs, uint flags, int item_sep)
1779
if (agg_item_collations(coll, fname, args, nargs, flags, item_sep))
1782
return agg_item_set_converter(coll, fname, args, nargs, flags, item_sep);
1786
void Item_ident_for_show::make_field(Send_field *tmp_field)
1788
tmp_field->table_name= tmp_field->org_table_name= table_name;
1789
tmp_field->db_name= db_name;
1790
tmp_field->col_name= tmp_field->org_col_name= field->field_name;
1791
tmp_field->charsetnr= field->charset()->number;
1792
tmp_field->length=field->field_length;
1793
tmp_field->type=field->type();
1794
tmp_field->flags= field->table->maybe_null ?
1795
(field->flags & ~NOT_NULL_FLAG) : field->flags;
1796
tmp_field->decimals= field->decimals();
1799
/**********************************************/
1801
Item_field::Item_field(Field *f)
1802
:Item_ident(0, NullS, *f->table_name, f->field_name),
1803
item_equal(0), no_const_subst(0),
1804
have_privileges(0), any_privileges(0)
1808
field_name and table_name should not point to garbage
1809
if this item is to be reused
1811
orig_table_name= orig_field_name= "";
1816
Constructor used inside setup_wild().
1818
Ensures that field, table, and database names will live as long as
1819
Item_field (this is important in prepared statements).
1822
Item_field::Item_field(THD *thd, Name_resolution_context *context_arg,
1824
:Item_ident(context_arg, f->table->s->db.str, *f->table_name, f->field_name),
1825
item_equal(0), no_const_subst(0),
1826
have_privileges(0), any_privileges(0)
1829
We always need to provide Item_field with a fully qualified field
1830
name to avoid ambiguity when executing prepared statements like
1831
SELECT * from d1.t1, d2.t1; (assuming d1.t1 and d2.t1 have columns
1833
This is because prepared statements never deal with wildcards in
1834
select list ('*') and always fix fields using fully specified path
1835
(i.e. db.table.column).
1836
No check for OOM: if db_name is NULL, we'll just get
1837
"Field not found" error.
1838
We need to copy db_name, table_name and field_name because they must
1839
be allocated in the statement memory, not in table memory (the table
1840
structure can go away and pop up again between subsequent executions
1841
of a prepared statement or after the close_tables_for_reopen() call
1842
in mysql_multi_update_prepare() or due to wildcard expansion in stored
1847
orig_db_name= thd->strdup(db_name);
1849
orig_table_name= thd->strdup(table_name);
1851
orig_field_name= thd->strdup(field_name);
1853
We don't restore 'name' in cleanup because it's not changed
1854
during execution. Still we need it to point to persistent
1855
memory if this item is to be reused.
1857
name= (char*) orig_field_name;
1863
Item_field::Item_field(Name_resolution_context *context_arg,
1864
const char *db_arg,const char *table_name_arg,
1865
const char *field_name_arg)
1866
:Item_ident(context_arg, db_arg,table_name_arg,field_name_arg),
1867
field(0), result_field(0), item_equal(0), no_const_subst(0),
1868
have_privileges(0), any_privileges(0)
1870
SELECT_LEX *select= current_thd->lex->current_select;
1871
collation.set(DERIVATION_IMPLICIT);
1872
if (select && select->parsing_place != IN_HAVING)
1873
select->select_n_where_fields++;
1877
Constructor need to process subselect with temporary tables (see Item)
1880
Item_field::Item_field(THD *thd, Item_field *item)
1881
:Item_ident(thd, item),
1883
result_field(item->result_field),
1884
item_equal(item->item_equal),
1885
no_const_subst(item->no_const_subst),
1886
have_privileges(item->have_privileges),
1887
any_privileges(item->any_privileges)
1889
collation.set(DERIVATION_IMPLICIT);
1892
void Item_field::set_field(Field *field_par)
1894
field=result_field=field_par; // for easy coding with fields
1895
maybe_null=field->maybe_null();
1896
decimals= field->decimals();
1897
max_length= field_par->max_display_length();
1898
table_name= *field_par->table_name;
1899
field_name= field_par->field_name;
1900
db_name= field_par->table->s->db.str;
1901
alias_name_used= field_par->table->alias_name_used;
1902
unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
1903
collation.set(field_par->charset(), field_par->derivation());
1905
if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
1911
Reset this item to point to a field from the new temporary table.
1912
This is used when we create a new temporary table for each execution
1913
of prepared statement.
1916
void Item_field::reset_field(Field *f)
1919
/* 'name' is pointing at field->field_name of old field */
1920
name= (char*) f->field_name;
1923
const char *Item_ident::full_name() const
1926
if (!table_name || !field_name)
1927
return field_name ? field_name : name ? name : "tmp_field";
1928
if (db_name && db_name[0])
1930
tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
1931
(uint) strlen(field_name)+3);
1932
strxmov(tmp,db_name,".",table_name,".",field_name,NullS);
1938
tmp= (char*) sql_alloc((uint) strlen(table_name) +
1939
(uint) strlen(field_name) + 2);
1940
strxmov(tmp, table_name, ".", field_name, NullS);
1943
tmp= (char*) field_name;
1948
void Item_ident::print(String *str, enum_query_type query_type)
1950
THD *thd= current_thd;
1951
char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
1952
const char *d_name= db_name, *t_name= table_name;
1953
if (lower_case_table_names== 1 ||
1954
(lower_case_table_names == 2 && !alias_name_used))
1956
if (table_name && table_name[0])
1958
strmov(t_name_buff, table_name);
1959
my_casedn_str(files_charset_info, t_name_buff);
1960
t_name= t_name_buff;
1962
if (db_name && db_name[0])
1964
strmov(d_name_buff, db_name);
1965
my_casedn_str(files_charset_info, d_name_buff);
1966
d_name= d_name_buff;
1970
if (!table_name || !field_name || !field_name[0])
1972
const char *nm= (field_name && field_name[0]) ?
1973
field_name : name ? name : "tmp_field";
1974
append_identifier(thd, str, nm, (uint) strlen(nm));
1977
if (db_name && db_name[0] && !alias_name_used)
1979
if (!(cached_table && cached_table->belong_to_view &&
1980
cached_table->belong_to_view->compact_view_format))
1982
append_identifier(thd, str, d_name, (uint)strlen(d_name));
1985
append_identifier(thd, str, t_name, (uint)strlen(t_name));
1987
append_identifier(thd, str, field_name, (uint)strlen(field_name));
1993
append_identifier(thd, str, t_name, (uint) strlen(t_name));
1995
append_identifier(thd, str, field_name, (uint) strlen(field_name));
1998
append_identifier(thd, str, field_name, (uint) strlen(field_name));
2003
String *Item_field::val_str(String *str)
2005
DBUG_ASSERT(fixed == 1);
2006
if ((null_value=field->is_null()))
2008
str->set_charset(str_value.charset());
2009
return field->val_str(str,&str_value);
2013
double Item_field::val_real()
2015
DBUG_ASSERT(fixed == 1);
2016
if ((null_value=field->is_null()))
2018
return field->val_real();
2022
longlong Item_field::val_int()
2024
DBUG_ASSERT(fixed == 1);
2025
if ((null_value=field->is_null()))
2027
return field->val_int();
2031
my_decimal *Item_field::val_decimal(my_decimal *decimal_value)
2033
if ((null_value= field->is_null()))
2035
return field->val_decimal(decimal_value);
2039
String *Item_field::str_result(String *str)
2041
if ((null_value=result_field->is_null()))
2043
str->set_charset(str_value.charset());
2044
return result_field->val_str(str,&str_value);
2047
bool Item_field::get_date(MYSQL_TIME *ltime,uint fuzzydate)
2049
if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
2051
bzero((char*) ltime,sizeof(*ltime));
2057
bool Item_field::get_date_result(MYSQL_TIME *ltime,uint fuzzydate)
2059
if ((null_value=result_field->is_null()) ||
2060
result_field->get_date(ltime,fuzzydate))
2062
bzero((char*) ltime,sizeof(*ltime));
2068
bool Item_field::get_time(MYSQL_TIME *ltime)
2070
if ((null_value=field->is_null()) || field->get_time(ltime))
2072
bzero((char*) ltime,sizeof(*ltime));
2078
double Item_field::val_result()
2080
if ((null_value=result_field->is_null()))
2082
return result_field->val_real();
2085
longlong Item_field::val_int_result()
2087
if ((null_value=result_field->is_null()))
2089
return result_field->val_int();
2093
my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value)
2095
if ((null_value= result_field->is_null()))
2097
return result_field->val_decimal(decimal_value);
2101
bool Item_field::val_bool_result()
2103
if ((null_value= result_field->is_null()))
2105
switch (result_field->result_type()) {
2107
return result_field->val_int() != 0;
2108
case DECIMAL_RESULT:
2110
my_decimal decimal_value;
2111
my_decimal *val= result_field->val_decimal(&decimal_value);
2113
return !my_decimal_is_zero(val);
2118
return result_field->val_real() != 0.0;
2122
return 0; // Shut up compiler
2127
bool Item_field::is_null_result()
2129
return (null_value=result_field->is_null());
2133
bool Item_field::eq(const Item *item, bool binary_cmp) const
2135
Item *real_item= ((Item *) item)->real_item();
2136
if (real_item->type() != FIELD_ITEM)
2139
Item_field *item_field= (Item_field*) real_item;
2140
if (item_field->field && field)
2141
return item_field->field == field;
2143
We may come here when we are trying to find a function in a GROUP BY
2144
clause from the select list.
2145
In this case the '100 % correct' way to do this would be to first
2146
run fix_fields() on the GROUP BY item and then retry this function, but
2147
I think it's better to relax the checking a bit as we will in
2148
most cases do the correct thing by just checking the field name.
2149
(In cases where we would choose wrong we would have to generate a
2152
return (!my_strcasecmp(system_charset_info, item_field->name,
2154
(!item_field->table_name || !table_name ||
2155
(!my_strcasecmp(table_alias_charset, item_field->table_name,
2157
(!item_field->db_name || !db_name ||
2158
(item_field->db_name && !strcmp(item_field->db_name,
2163
table_map Item_field::used_tables() const
2165
if (field->table->const_table)
2166
return 0; // const item
2167
return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
2171
Item *Item_field::get_tmp_table_item(THD *thd)
2173
Item_field *new_item= new Item_field(thd, this);
2175
new_item->field= new_item->result_field;
2179
longlong Item_field::val_int_endpoint(bool left_endp, bool *incl_endp)
2181
longlong res= val_int();
2182
return null_value? LONGLONG_MIN : res;
2186
Create an item from a string we KNOW points to a valid longlong
2187
end \\0 terminated number string.
2188
This is always 'signed'. Unsigned values are created with Item_uint()
2191
Item_int::Item_int(const char *str_arg, uint length)
2193
char *end_ptr= (char*) str_arg + length;
2195
value= my_strtoll10(str_arg, &end_ptr, &error);
2196
max_length= (uint) (end_ptr - str_arg);
2197
name= (char*) str_arg;
2202
my_decimal *Item_int::val_decimal(my_decimal *decimal_value)
2204
int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_value);
2205
return decimal_value;
2208
String *Item_int::val_str(String *str)
2210
// following assert is redundant, because fixed=1 assigned in constructor
2211
DBUG_ASSERT(fixed == 1);
2212
str->set_int(value, unsigned_flag, &my_charset_bin);
2216
void Item_int::print(String *str, enum_query_type query_type)
2218
// my_charset_bin is good enough for numbers
2219
str_value.set_int(value, unsigned_flag, &my_charset_bin);
2220
str->append(str_value);
2224
Item_uint::Item_uint(const char *str_arg, uint length):
2225
Item_int(str_arg, length)
2231
Item_uint::Item_uint(const char *str_arg, longlong i, uint length):
2232
Item_int(str_arg, i, length)
2238
String *Item_uint::val_str(String *str)
2240
// following assert is redundant, because fixed=1 assigned in constructor
2241
DBUG_ASSERT(fixed == 1);
2242
str->set((ulonglong) value, &my_charset_bin);
2247
void Item_uint::print(String *str, enum_query_type query_type)
2249
// latin1 is good enough for numbers
2250
str_value.set((ulonglong) value, default_charset());
2251
str->append(str_value);
2255
Item_decimal::Item_decimal(const char *str_arg, uint length,
2256
CHARSET_INFO *charset)
2258
str2my_decimal(E_DEC_FATAL_ERROR, str_arg, length, charset, &decimal_value);
2259
name= (char*) str_arg;
2260
decimals= (uint8) decimal_value.frac;
2262
max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
2268
Item_decimal::Item_decimal(longlong val, bool unsig)
2270
int2my_decimal(E_DEC_FATAL_ERROR, val, unsig, &decimal_value);
2271
decimals= (uint8) decimal_value.frac;
2273
max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
2280
Item_decimal::Item_decimal(double val, int precision, int scale)
2282
double2my_decimal(E_DEC_FATAL_ERROR, val, &decimal_value);
2283
decimals= (uint8) decimal_value.frac;
2285
max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
2292
Item_decimal::Item_decimal(const char *str, const my_decimal *val_arg,
2293
uint decimal_par, uint length)
2295
my_decimal2decimal(val_arg, &decimal_value);
2297
decimals= (uint8) decimal_par;
2303
Item_decimal::Item_decimal(my_decimal *value_par)
2305
my_decimal2decimal(value_par, &decimal_value);
2306
decimals= (uint8) decimal_value.frac;
2308
max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
2315
Item_decimal::Item_decimal(const uchar *bin, int precision, int scale)
2317
binary2my_decimal(E_DEC_FATAL_ERROR, bin,
2318
&decimal_value, precision, scale);
2319
decimals= (uint8) decimal_value.frac;
2321
max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
2326
longlong Item_decimal::val_int()
2329
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &result);
2333
double Item_decimal::val_real()
2336
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
2340
String *Item_decimal::val_str(String *result)
2342
result->set_charset(&my_charset_bin);
2343
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, result);
2347
void Item_decimal::print(String *str, enum_query_type query_type)
2349
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, &str_value);
2350
str->append(str_value);
2354
bool Item_decimal::eq(const Item *item, bool binary_cmp) const
2356
if (type() == item->type() && item->basic_const_item())
2359
We need to cast off const to call val_decimal(). This should
2360
be OK for a basic constant. Additionally, we can pass 0 as
2361
a true decimal constant will return its internal decimal
2362
storage and ignore the argument.
2364
Item *arg= (Item*) item;
2365
my_decimal *value= arg->val_decimal(0);
2366
return !my_decimal_cmp(&decimal_value, value);
2372
void Item_decimal::set_decimal_value(my_decimal *value_par)
2374
my_decimal2decimal(value_par, &decimal_value);
2375
decimals= (uint8) decimal_value.frac;
2376
unsigned_flag= !decimal_value.sign();
2377
max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
2384
String *Item_float::val_str(String *str)
2386
// following assert is redundant, because fixed=1 assigned in constructor
2387
DBUG_ASSERT(fixed == 1);
2388
str->set_real(value,decimals,&my_charset_bin);
2393
my_decimal *Item_float::val_decimal(my_decimal *decimal_value)
2395
// following assert is redundant, because fixed=1 assigned in constructor
2396
DBUG_ASSERT(fixed == 1);
2397
double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_value);
2398
return (decimal_value);
2402
void Item_string::print(String *str, enum_query_type query_type)
2404
if (query_type == QT_ORDINARY && is_cs_specified())
2407
str->append(collation.collation->csname);
2412
if (query_type == QT_ORDINARY ||
2413
my_charset_same(str_value.charset(), system_charset_info))
2415
str_value.print(str);
2419
THD *thd= current_thd;
2420
LEX_STRING utf8_lex_str;
2422
thd->convert_string(&utf8_lex_str,
2423
system_charset_info,
2424
str_value.c_ptr_safe(),
2426
str_value.charset());
2428
String utf8_str(utf8_lex_str.str,
2429
utf8_lex_str.length,
2430
system_charset_info);
2432
utf8_str.print(str);
2440
double_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end)
2447
tmp= my_strntod(cs, (char*) cptr, end - cptr, &end, &error);
2448
if (error || (end != org_end && !check_if_only_end_space(cs, end, org_end)))
2451
We can use str_value.ptr() here as Item_string is gurantee to put an
2454
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2455
ER_TRUNCATED_WRONG_VALUE,
2456
ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
2463
double Item_string::val_real()
2465
DBUG_ASSERT(fixed == 1);
2466
return double_from_string_with_check (str_value.charset(), str_value.ptr(),
2467
(char *) str_value.ptr() + str_value.length());
2472
longlong_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end)
2478
tmp= (*(cs->cset->strtoll10))(cs, cptr, &end, &err);
2480
TODO: Give error if we wanted a signed integer and we got an unsigned
2483
if (!current_thd->no_errors &&
2485
(end != org_end && !check_if_only_end_space(cs, end, org_end))))
2487
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2488
ER_TRUNCATED_WRONG_VALUE,
2489
ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
2498
Give error if we wanted a signed integer and we got an unsigned one
2500
longlong Item_string::val_int()
2502
DBUG_ASSERT(fixed == 1);
2503
return longlong_from_string_with_check(str_value.charset(), str_value.ptr(),
2504
(char *) str_value.ptr()+ str_value.length());
2508
my_decimal *Item_string::val_decimal(my_decimal *decimal_value)
2510
return val_decimal_from_string(decimal_value);
2514
bool Item_null::eq(const Item *item, bool binary_cmp) const
2515
{ return item->type() == type(); }
2518
double Item_null::val_real()
2520
// following assert is redundant, because fixed=1 assigned in constructor
2521
DBUG_ASSERT(fixed == 1);
2525
longlong Item_null::val_int()
2527
// following assert is redundant, because fixed=1 assigned in constructor
2528
DBUG_ASSERT(fixed == 1);
2533
String *Item_null::val_str(String *str)
2535
// following assert is redundant, because fixed=1 assigned in constructor
2536
DBUG_ASSERT(fixed == 1);
2541
my_decimal *Item_null::val_decimal(my_decimal *decimal_value)
2547
Item *Item_null::safe_charset_converter(CHARSET_INFO *tocs)
2549
collation.set(tocs);
2553
/*********************** Item_param related ******************************/
2556
Default function of Item_param::set_param_func, so in case
2557
of malformed packet the server won't SIGSEGV.
2561
default_set_param_func(Item_param *param,
2562
uchar **pos __attribute__((unused)),
2563
ulong len __attribute__((unused)))
2569
Item_param::Item_param(uint pos_in_query_arg) :
2571
item_result_type(STRING_RESULT),
2572
/* Don't pretend to be a literal unless value for this item is set. */
2573
item_type(PARAM_ITEM),
2574
param_type(MYSQL_TYPE_VARCHAR),
2575
pos_in_query(pos_in_query_arg),
2576
set_param_func(default_set_param_func),
2577
limit_clause_param(FALSE)
2581
Since we can't say whenever this item can be NULL or cannot be NULL
2582
before mysql_stmt_execute(), so we assuming that it can be NULL until
2586
cnvitem= new Item_string("", 0, &my_charset_bin, DERIVATION_COERCIBLE);
2587
cnvstr.set(cnvbuf, sizeof(cnvbuf), &my_charset_bin);
2591
void Item_param::set_null()
2593
DBUG_ENTER("Item_param::set_null");
2594
/* These are cleared after each execution by reset() method */
2597
Because of NULL and string values we need to set max_length for each new
2598
placeholder value: user can submit NULL for any placeholder type, and
2599
string length can be different in each execution.
2604
item_type= Item::NULL_ITEM;
2608
void Item_param::set_int(longlong i, uint32 max_length_arg)
2610
DBUG_ENTER("Item_param::set_int");
2611
value.integer= (longlong) i;
2613
max_length= max_length_arg;
2619
void Item_param::set_double(double d)
2621
DBUG_ENTER("Item_param::set_double");
2624
max_length= DBL_DIG + 8;
2625
decimals= NOT_FIXED_DEC;
2632
Set decimal parameter value from string.
2634
@param str character string
2635
@param length string length
2638
As we use character strings to send decimal values in
2639
binary protocol, we use str2my_decimal to convert it to
2640
internal decimal value.
2643
void Item_param::set_decimal(const char *str, ulong length)
2646
DBUG_ENTER("Item_param::set_decimal");
2648
end= (char*) str+length;
2649
str2my_decimal(E_DEC_FATAL_ERROR, str, &decimal_value, &end);
2650
state= DECIMAL_VALUE;
2651
decimals= decimal_value.frac;
2653
my_decimal_precision_to_length_no_truncation(decimal_value.precision(),
2654
decimals, unsigned_flag);
2661
Set parameter value from MYSQL_TIME value.
2663
@param tm datetime value to set (time_type is ignored)
2664
@param type type of datetime value
2665
@param max_length_arg max length of datetime value as string
2668
If we value to be stored is not normalized, zero value will be stored
2669
instead and proper warning will be produced. This function relies on
2670
the fact that even wrong value sent over binary protocol fits into
2671
MAX_DATE_STRING_REP_LENGTH buffer.
2673
void Item_param::set_time(MYSQL_TIME *tm, timestamp_type time_type,
2674
uint32 max_length_arg)
2676
DBUG_ENTER("Item_param::set_time");
2679
value.time.time_type= time_type;
2681
if (value.time.year > 9999 || value.time.month > 12 ||
2682
value.time.day > 31 ||
2683
(time_type != MYSQL_TIMESTAMP_TIME && value.time.hour > 23) ||
2684
value.time.minute > 59 || value.time.second > 59)
2686
char buff[MAX_DATE_STRING_REP_LENGTH];
2687
uint length= my_TIME_to_str(&value.time, buff);
2688
make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2689
buff, length, time_type, 0);
2690
set_zero_time(&value.time, MYSQL_TIMESTAMP_ERROR);
2695
max_length= max_length_arg;
2701
bool Item_param::set_str(const char *str, ulong length)
2703
DBUG_ENTER("Item_param::set_str");
2705
Assign string with no conversion: data is converted only after it's
2706
been written to the binary log.
2709
if (str_value.copy(str, length, &my_charset_bin, &my_charset_bin,
2712
state= STRING_VALUE;
2715
/* max_length and decimals are set after charset conversion */
2716
/* sic: str may be not null-terminated, don't add DBUG_PRINT here */
2721
bool Item_param::set_longdata(const char *str, ulong length)
2723
DBUG_ENTER("Item_param::set_longdata");
2726
If client character set is multibyte, end of long data packet
2727
may hit at the middle of a multibyte character. Additionally,
2728
if binary log is open we must write long data value to the
2729
binary log in character set of client. This is why we can't
2730
convert long data to connection character set as it comes
2731
(here), and first have to concatenate all pieces together,
2732
write query to the binary log and only then perform conversion.
2734
if (str_value.append(str, length, &my_charset_bin))
2736
state= LONG_DATA_VALUE;
2744
Set parameter value from user variable value.
2746
@param thd Current thread
2747
@param entry User variable structure (NULL means use NULL value)
2755
bool Item_param::set_from_user_var(THD *thd, const user_var_entry *entry)
2757
DBUG_ENTER("Item_param::set_from_user_var");
2758
if (entry && entry->value)
2760
item_result_type= entry->type;
2761
unsigned_flag= entry->unsigned_flag;
2762
if (limit_clause_param)
2765
set_int(entry->val_int(&unused), MY_INT64_NUM_DECIMAL_DIGITS);
2766
item_type= Item::INT_ITEM;
2767
DBUG_RETURN(!unsigned_flag && value.integer < 0 ? 1 : 0);
2769
switch (item_result_type) {
2771
set_double(*(double*)entry->value);
2772
item_type= Item::REAL_ITEM;
2775
set_int(*(longlong*)entry->value, MY_INT64_NUM_DECIMAL_DIGITS);
2776
item_type= Item::INT_ITEM;
2780
CHARSET_INFO *fromcs= entry->collation.collation;
2781
CHARSET_INFO *tocs= thd->variables.collation_connection;
2782
uint32 dummy_offset;
2784
value.cs_info.character_set_of_placeholder= fromcs;
2785
value.cs_info.character_set_client= thd->variables.character_set_client;
2787
Setup source and destination character sets so that they
2788
are different only if conversion is necessary: this will
2789
make later checks easier.
2791
value.cs_info.final_character_set_of_str_value=
2792
String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
2795
Exact value of max_length is not known unless data is converted to
2796
charset of connection, so we have to set it later.
2798
item_type= Item::STRING_ITEM;
2800
if (set_str((const char *)entry->value, entry->length))
2804
case DECIMAL_RESULT:
2806
const my_decimal *ent_value= (const my_decimal *)entry->value;
2807
my_decimal2decimal(ent_value, &decimal_value);
2808
state= DECIMAL_VALUE;
2809
decimals= ent_value->frac;
2811
my_decimal_precision_to_length_no_truncation(ent_value->precision(),
2812
decimals, unsigned_flag);
2813
item_type= Item::DECIMAL_ITEM;
2828
Resets parameter after execution.
2831
We clear null_value here instead of setting it in set_* methods,
2832
because we want more easily handle case for long data.
2835
void Item_param::reset()
2837
DBUG_ENTER("Item_param::reset");
2838
/* Shrink string buffer if it's bigger than max possible CHAR column */
2839
if (str_value.alloced_length() > MAX_CHAR_WIDTH)
2842
str_value.length(0);
2843
str_value_ptr.length(0);
2845
We must prevent all charset conversions until data has been written
2848
str_value.set_charset(&my_charset_bin);
2849
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
2854
Don't reset item_type to PARAM_ITEM: it's only needed to guard
2855
us from item optimizations at prepare stage, when item doesn't yet
2856
contain a literal of some kind.
2857
In all other cases when this object is accessed its value is
2858
set (this assumption is guarded by 'state' and
2859
DBUG_ASSERTS(state != NO_VALUE) in all Item_param::get_*
2866
int Item_param::save_in_field(Field *field, bool no_conversions)
2868
field->set_notnull();
2872
return field->store(value.integer, unsigned_flag);
2874
return field->store(value.real);
2876
return field->store_decimal(&decimal_value);
2878
field->store_time(&value.time, value.time.time_type);
2881
case LONG_DATA_VALUE:
2882
return field->store(str_value.ptr(), str_value.length(),
2883
str_value.charset());
2885
return set_field_to_null_with_conversions(field, no_conversions);
2894
bool Item_param::get_time(MYSQL_TIME *res)
2896
if (state == TIME_VALUE)
2902
If parameter value isn't supplied assertion will fire in val_str()
2903
which is called from Item::get_time().
2905
return Item::get_time(res);
2909
bool Item_param::get_date(MYSQL_TIME *res, uint fuzzydate)
2911
if (state == TIME_VALUE)
2916
return Item::get_date(res, fuzzydate);
2920
double Item_param::val_real()
2926
return (double) value.integer;
2930
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
2934
case LONG_DATA_VALUE:
2938
return my_strntod(str_value.charset(), (char*) str_value.ptr(),
2939
str_value.length(), &end_not_used, &dummy_err);
2943
This works for example when user says SELECT ?+0.0 and supplies
2944
time value for the placeholder.
2946
return ulonglong2double(TIME_to_ulonglong(&value.time));
2956
longlong Item_param::val_int()
2960
return (longlong) rint(value.real);
2962
return value.integer;
2966
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &i);
2970
case LONG_DATA_VALUE:
2973
return my_strntoll(str_value.charset(), str_value.ptr(),
2974
str_value.length(), 10, (char**) 0, &dummy_err);
2977
return (longlong) TIME_to_ulonglong(&value.time);
2987
my_decimal *Item_param::val_decimal(my_decimal *dec)
2991
return &decimal_value;
2993
double2my_decimal(E_DEC_FATAL_ERROR, value.real, dec);
2996
int2my_decimal(E_DEC_FATAL_ERROR, value.integer, unsigned_flag, dec);
2999
case LONG_DATA_VALUE:
3000
string2my_decimal(E_DEC_FATAL_ERROR, &str_value, dec);
3004
longlong i= (longlong) TIME_to_ulonglong(&value.time);
3005
int2my_decimal(E_DEC_FATAL_ERROR, i, 0, dec);
3017
String *Item_param::val_str(String* str)
3021
case LONG_DATA_VALUE:
3022
return &str_value_ptr;
3024
str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
3027
str->set(value.integer, &my_charset_bin);
3030
if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
3036
if (str->reserve(MAX_DATE_STRING_REP_LENGTH))
3038
str->length((uint) my_TIME_to_str(&value.time, (char*) str->ptr()));
3039
str->set_charset(&my_charset_bin);
3051
Return Param item values in string format, for generating the dynamic
3052
query used in update/binary logs.
3055
- Change interface and implementation to fill log data in place
3056
and avoid one more memcpy/alloc between str and log string.
3057
- In case of error we need to notify replication
3058
that binary log contains wrong statement
3061
const String *Item_param::query_val_str(String* str) const
3065
str->set_int(value.integer, unsigned_flag, &my_charset_bin);
3068
str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
3071
if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
3073
return &my_null_string;
3080
TODO: in case of error we need to notify replication
3081
that binary log contains wrong statement
3083
if (str->reserve(MAX_DATE_STRING_REP_LENGTH+3))
3086
/* Create date string inplace */
3087
buf= str->c_ptr_quick();
3090
ptr+= (uint) my_TIME_to_str(&value.time, ptr);
3092
str->length((uint32) (ptr - buf));
3096
case LONG_DATA_VALUE:
3099
append_query_string(value.cs_info.character_set_client, &str_value, str);
3103
return &my_null_string;
3112
Convert string from client character set to the character set of
3116
bool Item_param::convert_str_value(THD *thd)
3119
if (state == STRING_VALUE || state == LONG_DATA_VALUE)
3122
Check is so simple because all charsets were set up properly
3123
in setup_one_conversion_function, where typecode of
3124
placeholder was also taken into account: the variables are different
3125
here only if conversion is really necessary.
3127
if (value.cs_info.final_character_set_of_str_value !=
3128
value.cs_info.character_set_of_placeholder)
3130
rc= thd->convert_string(&str_value,
3131
value.cs_info.character_set_of_placeholder,
3132
value.cs_info.final_character_set_of_str_value);
3135
str_value.set_charset(value.cs_info.final_character_set_of_str_value);
3136
/* Here str_value is guaranteed to be in final_character_set_of_str_value */
3138
max_length= str_value.numchars() * str_value.charset()->mbmaxlen;
3141
str_value_ptr is returned from val_str(). It must be not alloced
3142
to prevent it's modification by val_str() invoker.
3144
str_value_ptr.set(str_value.ptr(), str_value.length(),
3145
str_value.charset());
3146
/* Synchronize item charset with value charset */
3147
collation.set(str_value.charset(), DERIVATION_COERCIBLE);
3153
bool Item_param::basic_const_item() const
3155
if (state == NO_VALUE || state == TIME_VALUE)
3162
Item_param::clone_item()
3164
/* see comments in the header file */
3167
return new Item_null(name);
3169
return (unsigned_flag ?
3170
new Item_uint(name, value.integer, max_length) :
3171
new Item_int(name, value.integer, max_length));
3173
return new Item_float(name, value.real, decimals, max_length);
3175
case LONG_DATA_VALUE:
3176
return new Item_string(name, str_value.c_ptr_quick(), str_value.length(),
3177
str_value.charset());
3189
Item_param::eq(const Item *arg, bool binary_cmp) const
3192
if (!basic_const_item() || !arg->basic_const_item() || arg->type() != type())
3195
We need to cast off const to call val_int(). This should be OK for
3204
return value.integer == item->val_int() &&
3205
unsigned_flag == item->unsigned_flag;
3207
return value.real == item->val_real();
3209
case LONG_DATA_VALUE:
3211
return !stringcmp(&str_value, &item->str_value);
3212
return !sortcmp(&str_value, &item->str_value, collation.collation);
3219
/* End of Item_param related */
3221
void Item_param::print(String *str, enum_query_type query_type)
3223
if (state == NO_VALUE)
3229
char buffer[STRING_BUFFER_USUAL_SIZE];
3230
String tmp(buffer, sizeof(buffer), &my_charset_bin);
3232
res= query_val_str(&tmp);
3239
Preserve the original parameter types and values
3240
when re-preparing a prepared statement.
3242
@details Copy parameter type information and conversion
3243
function pointers from a parameter of the old statement
3244
to the corresponding parameter of the new one.
3246
Move parameter values from the old parameters to the new
3247
one. We simply "exchange" the values, which allows
3248
to save on allocation and character set conversion in
3249
case a parameter is a string or a blob/clob.
3251
The old parameter gets the value of this one, which
3252
ensures that all memory of this parameter is freed
3255
@param[in] src parameter item of the original
3260
Item_param::set_param_type_and_swap_value(Item_param *src)
3262
unsigned_flag= src->unsigned_flag;
3263
param_type= src->param_type;
3264
set_param_func= src->set_param_func;
3265
item_type= src->item_type;
3266
item_result_type= src->item_result_type;
3268
collation.set(src->collation);
3269
maybe_null= src->maybe_null;
3270
null_value= src->null_value;
3271
max_length= src->max_length;
3272
decimals= src->decimals;
3276
decimal_value.swap(src->decimal_value);
3277
str_value.swap(src->str_value);
3278
str_value_ptr.swap(src->str_value_ptr);
3281
/****************************************************************************
3283
****************************************************************************/
3284
Item_copy *Item_copy::create (Item *item)
3286
switch (item->result_type())
3289
return new Item_copy_string (item);
3291
return new Item_copy_float (item);
3293
return item->unsigned_flag ?
3294
new Item_copy_uint (item) : new Item_copy_int (item);
3295
case DECIMAL_RESULT:
3296
return new Item_copy_decimal (item);
3300
/* should not happen */
3304
/****************************************************************************
3306
****************************************************************************/
3308
double Item_copy_string::val_real()
3312
return (null_value ? 0.0 :
3313
my_strntod(str_value.charset(), (char*) str_value.ptr(),
3314
str_value.length(), &end_not_used, &err_not_used));
3317
longlong Item_copy_string::val_int()
3320
return null_value ? LL(0) : my_strntoll(str_value.charset(),str_value.ptr(),
3321
str_value.length(),10, (char**) 0,
3326
int Item_copy_string::save_in_field(Field *field, bool no_conversions)
3328
return save_str_value_in_field(field, &str_value);
3332
void Item_copy_string::copy()
3334
String *res=item->val_str(&str_value);
3335
if (res && res != &str_value)
3336
str_value.copy(*res);
3337
null_value=item->null_value;
3341
String *Item_copy_string::val_str(String *str)
3343
// Item_copy_string is used without fix_fields call
3350
my_decimal *Item_copy_string::val_decimal(my_decimal *decimal_value)
3352
// Item_copy_string is used without fix_fields call
3354
return (my_decimal *) 0;
3355
string2my_decimal(E_DEC_FATAL_ERROR, &str_value, decimal_value);
3356
return (decimal_value);
3360
/****************************************************************************
3362
****************************************************************************/
3364
void Item_copy_int::copy()
3366
cached_value= item->val_int();
3367
null_value=item->null_value;
3370
static int save_int_value_in_field (Field *field, longlong nr,
3371
bool null_value, bool unsigned_flag);
3373
int Item_copy_int::save_in_field(Field *field, bool no_conversions)
3375
return save_int_value_in_field(field, cached_value,
3376
null_value, unsigned_flag);
3380
String *Item_copy_int::val_str(String *str)
3383
return (String *) 0;
3385
str->set(cached_value, &my_charset_bin);
3390
my_decimal *Item_copy_int::val_decimal(my_decimal *decimal_value)
3393
return (my_decimal *) 0;
3395
int2my_decimal(E_DEC_FATAL_ERROR, cached_value, unsigned_flag, decimal_value);
3396
return decimal_value;
3400
/****************************************************************************
3402
****************************************************************************/
3404
String *Item_copy_uint::val_str(String *str)
3407
return (String *) 0;
3409
str->set((ulonglong) cached_value, &my_charset_bin);
3414
/****************************************************************************
3416
****************************************************************************/
3418
String *Item_copy_float::val_str(String *str)
3421
return (String *) 0;
3424
double nr= val_real();
3425
str->set_real(nr,decimals, &my_charset_bin);
3431
my_decimal *Item_copy_float::val_decimal(my_decimal *decimal_value)
3434
return (my_decimal *) 0;
3437
double nr= val_real();
3438
double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
3439
return decimal_value;
3444
int Item_copy_float::save_in_field(Field *field, bool no_conversions)
3447
return set_field_to_null(field);
3448
field->set_notnull();
3449
return field->store(cached_value);
3453
/****************************************************************************
3455
****************************************************************************/
3457
int Item_copy_decimal::save_in_field(Field *field, bool no_conversions)
3460
return set_field_to_null(field);
3461
field->set_notnull();
3462
return field->store_decimal(&cached_value);
3466
String *Item_copy_decimal::val_str(String *result)
3469
return (String *) 0;
3470
result->set_charset(&my_charset_bin);
3471
my_decimal2string(E_DEC_FATAL_ERROR, &cached_value, 0, 0, 0, result);
3476
double Item_copy_decimal::val_real()
3483
my_decimal2double(E_DEC_FATAL_ERROR, &cached_value, &result);
3489
longlong Item_copy_decimal::val_int()
3496
my_decimal2int(E_DEC_FATAL_ERROR, &cached_value, unsigned_flag, &result);
3502
void Item_copy_decimal::copy()
3504
my_decimal *nr= item->val_decimal(&cached_value);
3505
if (nr && nr != &cached_value)
3506
memcpy (&cached_value, nr, sizeof (my_decimal));
3507
null_value= item->null_value;
3512
Functions to convert item to field (for send_fields)
3516
bool Item::fix_fields(THD *thd, Item **ref)
3519
// We do not check fields which are fixed during construction
3520
DBUG_ASSERT(fixed == 0 || basic_const_item());
3525
double Item_ref_null_helper::val_real()
3527
DBUG_ASSERT(fixed == 1);
3528
double tmp= (*ref)->val_result();
3529
owner->was_null|= null_value= (*ref)->null_value;
3534
longlong Item_ref_null_helper::val_int()
3536
DBUG_ASSERT(fixed == 1);
3537
longlong tmp= (*ref)->val_int_result();
3538
owner->was_null|= null_value= (*ref)->null_value;
3543
my_decimal *Item_ref_null_helper::val_decimal(my_decimal *decimal_value)
3545
DBUG_ASSERT(fixed == 1);
3546
my_decimal *val= (*ref)->val_decimal_result(decimal_value);
3547
owner->was_null|= null_value= (*ref)->null_value;
3552
bool Item_ref_null_helper::val_bool()
3554
DBUG_ASSERT(fixed == 1);
3555
bool val= (*ref)->val_bool_result();
3556
owner->was_null|= null_value= (*ref)->null_value;
3561
String* Item_ref_null_helper::val_str(String* s)
3563
DBUG_ASSERT(fixed == 1);
3564
String* tmp= (*ref)->str_result(s);
3565
owner->was_null|= null_value= (*ref)->null_value;
3570
bool Item_ref_null_helper::get_date(MYSQL_TIME *ltime, uint fuzzydate)
3572
return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate));
3577
Mark item and SELECT_LEXs as dependent if item was resolved in
3580
@param thd thread handler
3581
@param last select from which current item depend
3582
@param current current select
3583
@param resolved_item item which was resolved in outer SELECT(for warning)
3584
@param mark_item item which should be marked (can be differ in case of
3588
static void mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current,
3589
Item_ident *resolved_item,
3590
Item_ident *mark_item)
3592
const char *db_name= (resolved_item->db_name ?
3593
resolved_item->db_name : "");
3594
const char *table_name= (resolved_item->table_name ?
3595
resolved_item->table_name : "");
3596
/* store pointer on SELECT_LEX from which item is dependent */
3598
mark_item->depended_from= last;
3599
current->mark_as_dependent(last);
3600
if (thd->lex->describe & DESCRIBE_EXTENDED)
3602
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
3603
ER_WARN_FIELD_RESOLVED, ER(ER_WARN_FIELD_RESOLVED),
3604
db_name, (db_name[0] ? "." : ""),
3605
table_name, (table_name [0] ? "." : ""),
3606
resolved_item->field_name,
3607
current->select_number, last->select_number);
3613
Mark range of selects and resolved identifier (field/reference)
3616
@param thd thread handler
3617
@param last_select select where resolved_item was resolved
3618
@param current_sel current select (select where resolved_item was placed)
3619
@param found_field field which was found during resolving
3620
@param found_item Item which was found during resolving (if resolved
3621
identifier belongs to VIEW)
3622
@param resolved_item Identifier which was resolved
3625
We have to mark all items between current_sel (including) and
3626
last_select (excluding) as dependend (select before last_select should
3627
be marked with actual table mask used by resolved item, all other with
3628
OUTER_REF_TABLE_BIT) and also write dependence information to Item of
3629
resolved identifier.
3632
void mark_select_range_as_dependent(THD *thd,
3633
SELECT_LEX *last_select,
3634
SELECT_LEX *current_sel,
3635
Field *found_field, Item *found_item,
3636
Item_ident *resolved_item)
3639
Go from current SELECT to SELECT where field was resolved (it
3640
have to be reachable from current SELECT, because it was already
3641
done once when we resolved this field and cached result of
3644
SELECT_LEX *previous_select= current_sel;
3645
for (; previous_select->outer_select() != last_select;
3646
previous_select= previous_select->outer_select())
3648
Item_subselect *prev_subselect_item=
3649
previous_select->master_unit()->item;
3650
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
3651
prev_subselect_item->const_item_cache= 0;
3654
Item_subselect *prev_subselect_item=
3655
previous_select->master_unit()->item;
3656
Item_ident *dependent= resolved_item;
3657
if (found_field == view_ref_found)
3659
Item::Type type= found_item->type();
3660
prev_subselect_item->used_tables_cache|=
3661
found_item->used_tables();
3662
dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
3663
(Item_ident*) found_item :
3667
prev_subselect_item->used_tables_cache|=
3668
found_field->table->map;
3669
prev_subselect_item->const_item_cache= 0;
3670
mark_as_dependent(thd, last_select, current_sel, resolved_item,
3677
Search a GROUP BY clause for a field with a certain name.
3679
Search the GROUP BY list for a column named as find_item. When searching
3680
preference is given to columns that are qualified with the same table (and
3681
database) name as the one being searched for.
3683
@param find_item the item being searched for
3684
@param group_list GROUP BY clause
3687
- the found item on success
3688
- NULL if find_item is not in group_list
3691
static Item** find_field_in_group_list(Item *find_item, ORDER *group_list)
3693
const char *db_name;
3694
const char *table_name;
3695
const char *field_name;
3696
ORDER *found_group= NULL;
3697
int found_match_degree= 0;
3698
Item_ident *cur_field;
3699
int cur_match_degree= 0;
3700
char name_buff[NAME_LEN+1];
3702
if (find_item->type() == Item::FIELD_ITEM ||
3703
find_item->type() == Item::REF_ITEM)
3705
db_name= ((Item_ident*) find_item)->db_name;
3706
table_name= ((Item_ident*) find_item)->table_name;
3707
field_name= ((Item_ident*) find_item)->field_name;
3712
if (db_name && lower_case_table_names)
3714
/* Convert database to lower case for comparison */
3715
strmake(name_buff, db_name, sizeof(name_buff)-1);
3716
my_casedn_str(files_charset_info, name_buff);
3720
DBUG_ASSERT(field_name != 0);
3722
for (ORDER *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
3724
if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM)
3726
cur_field= (Item_ident*) *cur_group->item;
3727
cur_match_degree= 0;
3729
DBUG_ASSERT(cur_field->field_name != 0);
3731
if (!my_strcasecmp(system_charset_info,
3732
cur_field->field_name, field_name))
3737
if (cur_field->table_name && table_name)
3739
/* If field_name is qualified by a table name. */
3740
if (my_strcasecmp(table_alias_charset, cur_field->table_name, table_name))
3741
/* Same field names, different tables. */
3745
if (cur_field->db_name && db_name)
3747
/* If field_name is also qualified by a database name. */
3748
if (strcmp(cur_field->db_name, db_name))
3749
/* Same field names, different databases. */
3755
if (cur_match_degree > found_match_degree)
3757
found_match_degree= cur_match_degree;
3758
found_group= cur_group;
3760
else if (found_group && (cur_match_degree == found_match_degree) &&
3761
! (*(found_group->item))->eq(cur_field, 0))
3764
If the current resolve candidate matches equally well as the current
3765
best match, they must reference the same column, otherwise the field
3768
my_error(ER_NON_UNIQ_ERROR, MYF(0),
3769
find_item->full_name(), current_thd->where);
3776
return found_group->item;
3783
Resolve a column reference in a sub-select.
3785
Resolve a column reference (usually inside a HAVING clause) against the
3786
SELECT and GROUP BY clauses of the query described by 'select'. The name
3787
resolution algorithm searches both the SELECT and GROUP BY clauses, and in
3788
case of a name conflict prefers GROUP BY column names over SELECT names. If
3789
both clauses contain different fields with the same names, a warning is
3790
issued that name of 'ref' is ambiguous. We extend ANSI SQL in that when no
3791
GROUP BY column is found, then a HAVING name is resolved as a possibly
3792
derived SELECT column. This extension is allowed only if the
3793
MODE_ONLY_FULL_GROUP_BY sql mode isn't enabled.
3795
@param thd current thread
3796
@param ref column reference being resolved
3797
@param select the select that ref is resolved against
3800
The resolution procedure is:
3801
- Search for a column or derived column named col_ref_i [in table T_j]
3802
in the SELECT clause of Q.
3803
- Search for a column named col_ref_i [in table T_j]
3804
in the GROUP BY clause of Q.
3805
- If found different columns with the same name in GROUP BY and SELECT
3806
- issue a warning and return the GROUP BY column,
3808
- if the MODE_ONLY_FULL_GROUP_BY mode is enabled return error
3809
- else return the found SELECT column.
3813
- NULL - there was an error, and the error was already reported
3814
- not_found_item - the item was not resolved, no error was reported
3815
- resolved item - if the item was resolved
3819
resolve_ref_in_select_and_group(THD *thd, Item_ident *ref, SELECT_LEX *select)
3821
Item **group_by_ref= NULL;
3822
Item **select_ref= NULL;
3823
ORDER *group_list= (ORDER*) select->group_list.first;
3824
bool ambiguous_fields= FALSE;
3826
enum_resolution_type resolution;
3829
Search for a column or derived column named as 'ref' in the SELECT
3830
clause of the current select.
3832
if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()),
3833
&counter, REPORT_EXCEPT_NOT_FOUND,
3835
return NULL; /* Some error occurred. */
3836
if (resolution == RESOLVED_AGAINST_ALIAS)
3837
ref->alias_name_used= TRUE;
3839
/* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
3840
if (select->having_fix_field && !ref->with_sum_func && group_list)
3842
group_by_ref= find_field_in_group_list(ref, group_list);
3844
/* Check if the fields found in SELECT and GROUP BY are the same field. */
3845
if (group_by_ref && (select_ref != not_found_item) &&
3846
!((*group_by_ref)->eq(*select_ref, 0)))
3848
ambiguous_fields= TRUE;
3849
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
3850
ER(ER_NON_UNIQ_ERROR), ref->full_name(),
3851
current_thd->where);
3856
if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
3857
select->having_fix_field &&
3858
select_ref != not_found_item && !group_by_ref)
3861
Report the error if fields was found only in the SELECT item list and
3862
the strict mode is enabled.
3864
my_error(ER_NON_GROUPING_FIELD_USED, MYF(0),
3865
ref->name, "HAVING");
3868
if (select_ref != not_found_item || group_by_ref)
3870
if (select_ref != not_found_item && !ambiguous_fields)
3872
DBUG_ASSERT(*select_ref != 0);
3873
if (!select->ref_pointer_array[counter])
3875
my_error(ER_ILLEGAL_REFERENCE, MYF(0),
3876
ref->name, "forward reference in item list");
3879
DBUG_ASSERT((*select_ref)->fixed);
3880
return (select->ref_pointer_array + counter);
3883
return group_by_ref;
3885
return NULL; /* So there is no compiler warning. */
3888
return (Item**) not_found_item;
3893
Resolve the name of an outer select column reference.
3895
The method resolves the column reference represented by 'this' as a column
3896
present in outer selects that contain current select.
3898
In prepared statements, because of cache, find_field_in_tables()
3899
can resolve fields even if they don't belong to current context.
3900
In this case this method only finds appropriate context and marks
3901
current select as dependent. The found reference of field should be
3902
provided in 'from_field'.
3904
@param[in] thd current thread
3905
@param[in,out] from_field found field reference or (Field*)not_found_field
3906
@param[in,out] reference view column if this item was resolved to a
3910
This is the inner loop of Item_field::fix_fields:
3912
for each outer query Q_k beginning from the inner-most one
3914
search for a column or derived column named col_ref_i
3915
[in table T_j] in the FROM clause of Q_k;
3917
if such a column is not found
3918
Search for a column or derived column named col_ref_i
3919
[in table T_j] in the SELECT and GROUP clauses of Q_k.
3924
1 column succefully resolved and fix_fields() should continue.
3926
0 column fully fixed and fix_fields() should return FALSE
3932
Item_field::fix_outer_field(THD *thd, Field **from_field, Item **reference)
3934
enum_parsing_place place= NO_MATTER;
3935
bool field_found= (*from_field != not_found_field);
3936
bool upward_lookup= FALSE;
3939
If there are outer contexts (outer selects, but current select is
3940
not derived table or view) try to resolve this reference in the
3943
We treat each subselect as a separate namespace, so that different
3944
subselects may contain columns with the same names. The subselects
3945
are searched starting from the innermost.
3947
Name_resolution_context *last_checked_context= context;
3948
Item **ref= (Item **) not_found_item;
3949
SELECT_LEX *current_sel= (SELECT_LEX *) thd->lex->current_select;
3950
Name_resolution_context *outer_context= 0;
3951
SELECT_LEX *select= 0;
3952
/* Currently derived tables cannot be correlated */
3953
if (current_sel->master_unit()->first_select()->linkage !=
3955
outer_context= context->outer_context;
3958
outer_context= outer_context->outer_context)
3960
select= outer_context->select_lex;
3961
Item_subselect *prev_subselect_item=
3962
last_checked_context->select_lex->master_unit()->item;
3963
last_checked_context= outer_context;
3964
upward_lookup= TRUE;
3966
place= prev_subselect_item->parsing_place;
3968
If outer_field is set, field was already found by first call
3969
to find_field_in_tables(). Only need to find appropriate context.
3971
if (field_found && outer_context->select_lex !=
3972
cached_table->select_lex)
3975
In case of a view, find_field_in_tables() writes the pointer to
3976
the found view field into '*reference', in other words, it
3977
substitutes this Item_field with the found expression.
3979
if (field_found || (*from_field= find_field_in_tables(thd, this,
3981
first_name_resolution_table,
3983
last_name_resolution_table,
3985
IGNORE_EXCEPT_NON_UNIQUE,
3991
if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
3992
select->cur_pos_in_select_list != UNDEF_POS)
3995
As this is an outer field it should be added to the list of
3996
non aggregated fields of the outer select.
3998
marker= select->cur_pos_in_select_list;
3999
select->non_agg_fields.push_back(this);
4001
if (*from_field != view_ref_found)
4003
prev_subselect_item->used_tables_cache|= (*from_field)->table->map;
4004
prev_subselect_item->const_item_cache= 0;
4005
set_field(*from_field);
4006
if (!last_checked_context->select_lex->having_fix_field &&
4007
select->group_list.elements &&
4008
(place == SELECT_LIST || place == IN_HAVING))
4012
If an outer field is resolved in a grouping select then it
4013
is replaced for an Item_outer_ref object. Otherwise an
4014
Item_field object is used.
4015
The new Item_outer_ref object is saved in the inner_refs_list of
4016
the outer select. Here it is only created. It can be fixed only
4017
after the original field has been fixed and this is done in the
4018
fix_inner_refs() function.
4021
if (!(rf= new Item_outer_ref(context, this)))
4023
thd->change_item_tree(reference, rf);
4024
select->inner_refs_list.push_back(rf);
4025
rf->in_sum_func= thd->lex->in_sum_func;
4028
A reference is resolved to a nest level that's outer or the same as
4029
the nest level of the enclosing set function : adjust the value of
4030
max_arg_level for the function if it's needed.
4032
if (thd->lex->in_sum_func &&
4033
thd->lex->in_sum_func->nest_level >= select->nest_level)
4035
Item::Type ref_type= (*reference)->type();
4036
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
4037
select->nest_level);
4038
set_field(*from_field);
4040
mark_as_dependent(thd, last_checked_context->select_lex,
4041
context->select_lex, this,
4042
((ref_type == REF_ITEM ||
4043
ref_type == FIELD_ITEM) ?
4044
(Item_ident*) (*reference) : 0));
4050
Item::Type ref_type= (*reference)->type();
4051
prev_subselect_item->used_tables_cache|=
4052
(*reference)->used_tables();
4053
prev_subselect_item->const_item_cache&=
4054
(*reference)->const_item();
4055
mark_as_dependent(thd, last_checked_context->select_lex,
4056
context->select_lex, this,
4057
((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ?
4058
(Item_ident*) (*reference) :
4061
A reference to a view field had been found and we
4062
substituted it instead of this Item (find_field_in_tables
4063
does it by assigning the new value to *reference), so now
4064
we can return from this function.
4072
/* Search in SELECT and GROUP lists of the outer select. */
4073
if (place != IN_WHERE && place != IN_ON)
4075
if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
4076
return -1; /* Some error occurred (e.g. ambiguous names). */
4077
if (ref != not_found_item)
4079
DBUG_ASSERT(*ref && (*ref)->fixed);
4080
prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
4081
prev_subselect_item->const_item_cache&= (*ref)->const_item();
4087
Reference is not found in this select => this subquery depend on
4088
outer select (or we just trying to find wrong identifier, in this
4089
case it does not matter which used tables bits we set)
4091
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
4092
prev_subselect_item->const_item_cache= 0;
4095
DBUG_ASSERT(ref != 0);
4098
if (ref == not_found_item && *from_field == not_found_field)
4102
// We can't say exactly what absent table or field
4103
my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where);
4107
/* Call find_field_in_tables only to report the error */
4108
find_field_in_tables(thd, this,
4109
context->first_name_resolution_table,
4110
context->last_name_resolution_table,
4111
reference, REPORT_ALL_ERRORS,
4117
else if (ref != not_found_item)
4122
/* Should have been checked in resolve_ref_in_select_and_group(). */
4123
DBUG_ASSERT(*ref && (*ref)->fixed);
4125
Here, a subset of actions performed by Item_ref::set_properties
4126
is not enough. So we pass ptr to NULL into Item_[direct]_ref
4127
constructor, so no initialization is performed, and call
4131
*ref= NULL; // Don't call set_properties()
4132
rf= (place == IN_HAVING ?
4133
new Item_ref(context, ref, (char*) table_name,
4134
(char*) field_name, alias_name_used) :
4135
(!select->group_list.elements ?
4136
new Item_direct_ref(context, ref, (char*) table_name,
4137
(char*) field_name, alias_name_used) :
4138
new Item_outer_ref(context, ref, (char*) table_name,
4139
(char*) field_name, alias_name_used)));
4144
if (place != IN_HAVING && select->group_list.elements)
4146
outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf);
4147
((Item_outer_ref*)rf)->in_sum_func= thd->lex->in_sum_func;
4149
thd->change_item_tree(reference, rf);
4151
rf is Item_ref => never substitute other items (in this case)
4152
during fix_fields() => we can use rf after fix_fields()
4154
DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
4155
if (rf->fix_fields(thd, reference) || rf->check_cols(1))
4158
mark_as_dependent(thd, last_checked_context->select_lex,
4159
context->select_lex, this,
4165
mark_as_dependent(thd, last_checked_context->select_lex,
4166
context->select_lex,
4167
this, (Item_ident*)*reference);
4168
if (last_checked_context->select_lex->having_fix_field)
4171
rf= new Item_ref(context,
4172
(cached_table->db[0] ? cached_table->db : 0),
4173
(char*) cached_table->alias, (char*) field_name);
4176
thd->change_item_tree(reference, rf);
4178
rf is Item_ref => never substitute other items (in this case)
4179
during fix_fields() => we can use rf after fix_fields()
4181
DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
4182
if (rf->fix_fields(thd, reference) || rf->check_cols(1))
4192
Resolve the name of a column reference.
4194
The method resolves the column reference represented by 'this' as a column
4195
present in one of: FROM clause, SELECT clause, GROUP BY clause of a query
4196
Q, or in outer queries that contain Q.
4198
The name resolution algorithm used is (where [T_j] is an optional table
4199
name that qualifies the column name):
4202
resolve_column_reference([T_j].col_ref_i)
4204
search for a column or derived column named col_ref_i
4205
[in table T_j] in the FROM clause of Q;
4207
if such a column is NOT found AND // Lookup in outer queries.
4208
there are outer queries
4210
for each outer query Q_k beginning from the inner-most one
4212
search for a column or derived column named col_ref_i
4213
[in table T_j] in the FROM clause of Q_k;
4215
if such a column is not found
4216
Search for a column or derived column named col_ref_i
4217
[in table T_j] in the SELECT and GROUP clauses of Q_k.
4223
Notice that compared to Item_ref::fix_fields, here we first search the FROM
4224
clause, and then we search the SELECT and GROUP BY clauses.
4226
@param[in] thd current thread
4227
@param[in,out] reference view column if this item was resolved to a
4236
bool Item_field::fix_fields(THD *thd, Item **reference)
4238
DBUG_ASSERT(fixed == 0);
4239
Field *from_field= (Field *)not_found_field;
4240
bool outer_fixed= false;
4242
if (!field) // If field is not checked
4245
In case of view, find_field_in_tables() write pointer to view field
4246
expression to 'reference', i.e. it substitute that expression instead
4249
if ((from_field= find_field_in_tables(thd, this,
4250
context->first_name_resolution_table,
4251
context->last_name_resolution_table,
4253
thd->lex->use_only_table_context ?
4255
IGNORE_EXCEPT_NON_UNIQUE,
4261
/* Look up in current select's item_list to find aliased fields */
4262
if (thd->lex->current_select->is_item_list_lookup)
4265
enum_resolution_type resolution;
4266
Item** res= find_item_in_list(this, thd->lex->current_select->item_list,
4267
&counter, REPORT_EXCEPT_NOT_FOUND,
4271
if (resolution == RESOLVED_AGAINST_ALIAS)
4272
alias_name_used= TRUE;
4273
if (res != (Item **)not_found_item)
4275
if ((*res)->type() == Item::FIELD_ITEM)
4278
It's an Item_field referencing another Item_field in the select
4280
Use the field from the Item_field in the select list and leave
4281
the Item_field instance in place.
4284
Field *new_field= (*((Item_field**)res))->field;
4286
if (new_field == NULL)
4288
/* The column to which we link isn't valid. */
4289
my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->name,
4290
current_thd->where);
4294
set_field(new_field);
4300
It's not an Item_field in the select list so we must make a new
4301
Item_ref to point to the Item in the select list and replace the
4302
Item_field created by the parser with the new Item_ref.
4304
NOTE: If we are fixing an alias reference inside ORDER/GROUP BY
4305
item tree, then we use new Item_ref as an intermediate value
4306
to resolve referenced item only.
4307
In this case the new Item_ref item is unused.
4309
Item_ref *rf= new Item_ref(context, db_name,table_name,field_name);
4313
bool save_group_fix_field= thd->lex->current_select->group_fix_field;
4315
No need for recursive resolving of aliases.
4317
thd->lex->current_select->group_fix_field= 0;
4319
bool ret= rf->fix_fields(thd, (Item **) &rf) || rf->check_cols(1);
4320
thd->lex->current_select->group_fix_field= save_group_fix_field;
4324
if (save_group_fix_field && alias_name_used)
4325
thd->change_item_tree(reference, *rf->ref);
4327
thd->change_item_tree(reference, rf);
4333
if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
4337
goto mark_non_agg_field;
4339
else if (!from_field)
4342
if (!outer_fixed && cached_table && cached_table->select_lex &&
4343
context->select_lex &&
4344
cached_table->select_lex != context->select_lex)
4347
if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
4351
goto mark_non_agg_field;
4355
if it is not expression from merged VIEW we will set this field.
4357
We can leave expression substituted from view for next PS/SP rexecution
4358
(i.e. do not register this substitution for reverting on cleanup()
4359
(register_item_tree_changing())), because this subtree will be
4360
fix_field'ed during setup_tables()->setup_underlying() (i.e. before
4361
all other expressions of query, and references on tables which do
4362
not present in query will not make problems.
4364
Also we suppose that view can't be changed during PS/SP life.
4366
if (from_field == view_ref_found)
4369
set_field(from_field);
4370
if (thd->lex->in_sum_func &&
4371
thd->lex->in_sum_func->nest_level ==
4372
thd->lex->current_select->nest_level)
4373
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
4374
thd->lex->current_select->nest_level);
4376
else if (thd->mark_used_columns != MARK_COLUMNS_NONE)
4378
TABLE *table= field->table;
4379
MY_BITMAP *current_bitmap, *other_bitmap;
4380
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4382
current_bitmap= table->read_set;
4383
other_bitmap= table->write_set;
4387
current_bitmap= table->write_set;
4388
other_bitmap= table->read_set;
4390
if (!bitmap_fast_test_and_set(current_bitmap, field->field_index))
4392
if (!bitmap_is_set(other_bitmap, field->field_index))
4394
/* First usage of column */
4395
table->used_fields++; // Used to optimize loops
4396
/* purecov: begin inspected */
4397
table->covering_keys.intersect(field->part_of_key);
4402
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4406
db= cached_table->get_db_name();
4407
tab= cached_table->get_table_name();
4408
if (!(have_privileges= (get_column_grant(thd, &field->table->grant,
4409
db, tab, field_name) &
4412
my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
4413
"ANY", thd->security_ctx->priv_user,
4414
thd->security_ctx->host_or_ip, field_name, tab);
4420
if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
4421
!outer_fixed && !thd->lex->in_sum_func &&
4422
thd->lex->current_select->cur_pos_in_select_list != UNDEF_POS)
4424
thd->lex->current_select->non_agg_fields.push_back(this);
4425
marker= thd->lex->current_select->cur_pos_in_select_list;
4428
if (fixed && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
4431
Mark selects according to presence of non aggregated fields.
4432
Fields from outer selects added to the aggregate function
4433
outer_fields list as its unknown at the moment whether it's
4435
We're using either the select lex of the cached table (if present)
4436
or the field's resolution context. context->select_lex is
4437
safe for use because it's either the SELECT we want to use
4438
(the current level) or a stub added by non-SELECT queries.
4440
SELECT_LEX *select_lex= cached_table ?
4441
cached_table->select_lex : context->select_lex;
4442
if (!thd->lex->in_sum_func)
4443
select_lex->full_group_by_flag|= NON_AGG_FIELD_USED;
4447
thd->lex->in_sum_func->outer_fields.push_back(this);
4448
else if (thd->lex->in_sum_func->nest_level !=
4449
thd->lex->current_select->nest_level)
4450
select_lex->full_group_by_flag|= NON_AGG_FIELD_USED;
4456
context->process_error(thd);
4461
Item *Item_field::safe_charset_converter(CHARSET_INFO *tocs)
4464
return Item::safe_charset_converter(tocs);
4468
void Item_field::cleanup()
4470
DBUG_ENTER("Item_field::cleanup");
4471
Item_ident::cleanup();
4473
Even if this object was created by direct link to field in setup_wild()
4474
it will be linked correctly next time by name of field and table alias.
4475
I.e. we can drop 'field'.
4477
field= result_field= 0;
4483
Find a field among specified multiple equalities.
4485
The function first searches the field among multiple equalities
4486
of the current level (in the cond_equal->current_level list).
4487
If it fails, it continues searching in upper levels accessed
4488
through a pointer cond_equal->upper_levels.
4489
The search terminates as soon as a multiple equality containing
4492
@param cond_equal reference to list of multiple equalities where
4493
the field (this object) is to be looked for
4496
- First Item_equal containing the field, if success
4500
Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal)
4502
Item_equal *item= 0;
4505
List_iterator_fast<Item_equal> li(cond_equal->current_level);
4506
while ((item= li++))
4508
if (item->contains(field))
4512
The field is not found in any of the multiple equalities
4513
of the current level. Look for it in upper levels
4515
cond_equal= cond_equal->upper_levels;
4522
Check whether a field can be substituted by an equal item.
4524
The function checks whether a substitution of the field
4525
occurrence for an equal item is valid.
4527
@param arg *arg != NULL <-> the field is in the context where
4528
substitution for an equal item is valid
4531
The following statement is not always true:
4535
This means substitution of an item for an equal item not always
4536
yields an equavalent condition. Here's an example:
4539
(LENGTH('a')=1) != (LENGTH('a ')=2)
4541
Such a substitution is surely valid if either the substituted
4542
field is not of a STRING type or if it is an argument of
4543
a comparison predicate.
4546
TRUE substitution is valid
4551
bool Item_field::subst_argument_checker(uchar **arg)
4553
return (result_type() != STRING_RESULT) || (*arg);
4558
Convert a numeric value to a zero-filled string
4560
@param[in,out] item the item to operate on
4561
@param field The field that this value is equated to
4563
This function converts a numeric value to a string. In this conversion
4564
the zero-fill flag of the field is taken into account.
4565
This is required so the resulting string value can be used instead of
4566
the field reference when propagating equalities.
4569
static void convert_zerofill_number_to_string(Item **item, Field_num *field)
4571
char buff[MAX_FIELD_WIDTH],*pos;
4572
String tmp(buff,sizeof(buff), field->charset()), *res;
4574
res= (*item)->val_str(&tmp);
4575
if ((*item)->is_null())
4576
*item= new Item_null();
4579
field->prepend_zeros(res);
4580
pos= (char *) sql_strmake (res->ptr(), res->length());
4581
*item= new Item_string(pos, res->length(), field->charset());
4587
Set a pointer to the multiple equality the field reference belongs to
4590
The function looks for a multiple equality containing the field item
4591
among those referenced by arg.
4592
In the case such equality exists the function does the following.
4593
If the found multiple equality contains a constant, then the field
4594
reference is substituted for this constant, otherwise it sets a pointer
4595
to the multiple equality in the field item.
4598
@param arg reference to list of multiple equalities where
4599
the field (this object) is to be looked for
4602
This function is supposed to be called as a callback parameter in calls
4603
of the compile method.
4606
- pointer to the replacing constant item, if the field item was substituted
4607
- pointer to the field item, otherwise.
4610
Item *Item_field::equal_fields_propagator(uchar *arg)
4614
item_equal= find_item_equal((COND_EQUAL *) arg);
4617
item= item_equal->get_const();
4619
Disable const propagation for items used in different comparison contexts.
4620
This must be done because, for example, Item_hex_string->val_int() is not
4621
the same as (Item_hex_string->val_str() in BINARY column)->val_int().
4622
We cannot simply disable the replacement in a particular context (
4623
e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
4624
Items don't know the context they are in and there are functions like
4625
IF (<hex_string>, 'yes', 'no').
4626
The same problem occurs when comparing a DATE/TIME field with a
4627
DATE/TIME represented as an int and as a string.
4630
(cmp_context != (Item_result)-1 && item->cmp_context != cmp_context))
4632
else if (field && (field->flags & ZEROFILL_FLAG) && IS_NUM(field->type()))
4635
We don't need to zero-fill timestamp columns here because they will be
4636
first converted to a string (in date/time format) and compared as such if
4637
compared with another string.
4639
if (item && field->type() != FIELD_TYPE_TIMESTAMP && cmp_context != INT_RESULT)
4640
convert_zerofill_number_to_string(&item, (Field_num *)field);
4649
Mark the item to not be part of substitution if it's not a binary item.
4651
See comments in Arg_comparator::set_compare_func() for details.
4654
bool Item_field::set_no_const_sub(uchar *arg)
4656
if (field->charset() != &my_charset_bin)
4663
Replace an Item_field for an equal Item_field that evaluated earlier
4666
The function returns a pointer to an item that is taken from
4667
the very beginning of the item_equal list which the Item_field
4668
object refers to (belongs to) unless item_equal contains a constant
4669
item. In this case the function returns this constant item,
4670
(if the substitution does not require conversion).
4671
If the Item_field object does not refer any Item_equal object
4672
'this' is returned .
4674
@param arg a dummy parameter, is not used here
4678
This function is supposed to be called as a callback parameter in calls
4679
of the thransformer method.
4682
- pointer to a replacement Item_field if there is a better equal item or
4683
a pointer to a constant equal item;
4687
Item *Item_field::replace_equal_field(uchar *arg)
4691
Item *const_item= item_equal->get_const();
4694
if (cmp_context != (Item_result)-1 &&
4695
const_item->cmp_context != cmp_context)
4699
Item_field *subst= item_equal->get_first();
4700
if (subst && field->table != subst->field->table && !field->eq(subst->field))
4707
void Item::init_make_field(Send_field *tmp_field,
4708
enum enum_field_types field_type_arg)
4710
char *empty_name= (char*) "";
4711
tmp_field->db_name= empty_name;
4712
tmp_field->org_table_name= empty_name;
4713
tmp_field->org_col_name= empty_name;
4714
tmp_field->table_name= empty_name;
4715
tmp_field->col_name= name;
4716
tmp_field->charsetnr= collation.collation->number;
4717
tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
4718
(my_binary_compare(collation.collation) ?
4720
tmp_field->type= field_type_arg;
4721
tmp_field->length=max_length;
4722
tmp_field->decimals=decimals;
4724
tmp_field->flags |= UNSIGNED_FLAG;
4727
void Item::make_field(Send_field *tmp_field)
4729
init_make_field(tmp_field, field_type());
4733
enum_field_types Item::string_field_type() const
4735
enum_field_types f_type= MYSQL_TYPE_VAR_STRING;
4736
if (max_length >= 16777216)
4737
f_type= MYSQL_TYPE_LONG_BLOB;
4738
else if (max_length >= 65536)
4739
f_type= MYSQL_TYPE_MEDIUM_BLOB;
4744
void Item_empty_string::make_field(Send_field *tmp_field)
4746
init_make_field(tmp_field, string_field_type());
4750
enum_field_types Item::field_type() const
4752
switch (result_type()) {
4753
case STRING_RESULT: return string_field_type();
4754
case INT_RESULT: return MYSQL_TYPE_LONGLONG;
4755
case DECIMAL_RESULT: return MYSQL_TYPE_NEWDECIMAL;
4756
case REAL_RESULT: return MYSQL_TYPE_DOUBLE;
4760
return MYSQL_TYPE_VARCHAR;
4765
bool Item::is_datetime()
4767
switch (field_type())
4769
case MYSQL_TYPE_DATE:
4770
case MYSQL_TYPE_DATETIME:
4771
case MYSQL_TYPE_TIMESTAMP:
4780
String *Item::check_well_formed_result(String *str, bool send_error)
4782
/* Check whether we got a well-formed string */
4783
CHARSET_INFO *cs= str->charset();
4784
int well_formed_error;
4785
uint wlen= cs->cset->well_formed_len(cs,
4786
str->ptr(), str->ptr() + str->length(),
4787
str->length(), &well_formed_error);
4788
if (wlen < str->length())
4790
THD *thd= current_thd;
4792
enum MYSQL_ERROR::enum_warning_level level;
4793
uint diff= str->length() - wlen;
4794
set_if_smaller(diff, 3);
4795
octet2hex(hexbuf, str->ptr() + wlen, diff);
4798
my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
4799
cs->csname, hexbuf);
4802
if ((thd->variables.sql_mode &
4803
(MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)))
4805
level= MYSQL_ERROR::WARN_LEVEL_ERROR;
4811
level= MYSQL_ERROR::WARN_LEVEL_WARN;
4814
push_warning_printf(thd, level, ER_INVALID_CHARACTER_STRING,
4815
ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
4821
Compare two items using a given collation
4825
item item to compare with
4826
binary_cmp TRUE <-> compare as binaries
4827
cs collation to use when comparing strings
4830
This method works exactly as Item::eq if the collation cs coincides with
4831
the collation of the compared objects. Otherwise, first the collations that
4832
differ from cs are replaced for cs and then the items are compared by
4833
Item::eq. After the comparison the original collations of items are
4837
1 compared items has been detected as equal
4841
bool Item::eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs)
4843
CHARSET_INFO *save_cs= 0;
4844
CHARSET_INFO *save_item_cs= 0;
4845
if (collation.collation != cs)
4847
save_cs= collation.collation;
4848
collation.collation= cs;
4850
if (item->collation.collation != cs)
4852
save_item_cs= item->collation.collation;
4853
item->collation.collation= cs;
4855
bool res= eq(item, binary_cmp);
4857
collation.collation= save_cs;
4859
item->collation.collation= save_item_cs;
4865
Create a field to hold a string value from an item.
4867
If max_length > CONVERT_IF_BIGGER_TO_BLOB create a blob @n
4868
If max_length > 0 create a varchar @n
4869
If max_length == 0 create a CHAR(0)
4871
@param table Table for which the field is created
4874
Field *Item::make_string_field(TABLE *table)
4877
DBUG_ASSERT(collation.collation);
4878
if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB)
4879
field= new Field_blob(max_length, maybe_null, name,
4880
collation.collation);
4881
/* Item_type_holder holds the exact type, do not change it */
4882
else if (max_length > 0 &&
4883
(type() != Item::TYPE_HOLDER || field_type() != MYSQL_TYPE_STRING))
4884
field= new Field_varstring(max_length, maybe_null, name, table->s,
4885
collation.collation);
4887
field= new Field_string(max_length, maybe_null, name,
4888
collation.collation);
4896
Create a field based on field_type of argument.
4898
For now, this is only used to create a field for
4899
IFNULL(x,something) and time functions
4907
Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length)
4910
The field functions defines a field to be not null if null_ptr is not 0
4912
uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
4915
switch (field_type()) {
4916
case MYSQL_TYPE_DECIMAL:
4917
case MYSQL_TYPE_NEWDECIMAL:
4918
field= Field_new_decimal::create_from_item(this);
4920
case MYSQL_TYPE_TINY:
4921
field= new Field_tiny((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4922
name, 0, unsigned_flag);
4924
case MYSQL_TYPE_SHORT:
4925
field= new Field_short((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4926
name, 0, unsigned_flag);
4928
case MYSQL_TYPE_LONG:
4929
field= new Field_long((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4930
name, 0, unsigned_flag);
4932
#ifdef HAVE_LONG_LONG
4933
case MYSQL_TYPE_LONGLONG:
4934
field= new Field_longlong((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4935
name, 0, unsigned_flag);
4938
case MYSQL_TYPE_FLOAT:
4939
field= new Field_float((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4940
name, decimals, 0, unsigned_flag);
4942
case MYSQL_TYPE_DOUBLE:
4943
field= new Field_double((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4944
name, decimals, 0, unsigned_flag);
4946
case MYSQL_TYPE_NULL:
4947
field= new Field_null((uchar*) 0, max_length, Field::NONE,
4948
name, &my_charset_bin);
4950
case MYSQL_TYPE_INT24:
4951
field= new Field_medium((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4952
name, 0, unsigned_flag);
4954
case MYSQL_TYPE_NEWDATE:
4955
case MYSQL_TYPE_DATE:
4956
field= new Field_newdate(maybe_null, name, &my_charset_bin);
4958
case MYSQL_TYPE_TIME:
4959
field= new Field_time(maybe_null, name, &my_charset_bin);
4961
case MYSQL_TYPE_TIMESTAMP:
4962
field= new Field_timestamp(maybe_null, name, &my_charset_bin);
4964
case MYSQL_TYPE_DATETIME:
4965
field= new Field_datetime(maybe_null, name, &my_charset_bin);
4967
case MYSQL_TYPE_YEAR:
4968
field= new Field_year((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4971
case MYSQL_TYPE_BIT:
4972
field= new Field_bit_as_char(NULL, max_length, null_ptr, 0,
4976
/* This case should never be chosen */
4978
/* If something goes awfully wrong, it's better to get a string than die */
4979
case MYSQL_TYPE_STRING:
4980
if (fixed_length && max_length < CONVERT_IF_BIGGER_TO_BLOB)
4982
field= new Field_string(max_length, maybe_null, name,
4983
collation.collation);
4986
/* Fall through to make_string_field() */
4987
case MYSQL_TYPE_ENUM:
4988
case MYSQL_TYPE_SET:
4989
case MYSQL_TYPE_VAR_STRING:
4990
case MYSQL_TYPE_VARCHAR:
4991
return make_string_field(table);
4992
case MYSQL_TYPE_TINY_BLOB:
4993
case MYSQL_TYPE_MEDIUM_BLOB:
4994
case MYSQL_TYPE_LONG_BLOB:
4995
case MYSQL_TYPE_BLOB:
4996
if (this->type() == Item::TYPE_HOLDER)
4997
field= new Field_blob(max_length, maybe_null, name, collation.collation,
5000
field= new Field_blob(max_length, maybe_null, name, collation.collation);
5001
break; // Blob handled outside of case
5003
case MYSQL_TYPE_GEOMETRY:
5004
field= new Field_geom(max_length, maybe_null,
5005
name, table->s, get_geometry_type());
5006
#endif /* HAVE_SPATIAL */
5015
void Item_field::make_field(Send_field *tmp_field)
5017
field->make_field(tmp_field);
5018
DBUG_ASSERT(tmp_field->table_name != 0);
5020
tmp_field->col_name=name; // Use user supplied name
5022
tmp_field->table_name= table_name;
5024
tmp_field->db_name= db_name;
5029
Set a field's value from a item.
5032
void Item_field::save_org_in_field(Field *to)
5034
if (field->is_null())
5037
set_field_to_null_with_conversions(to, 1);
5042
field_conv(to,field);
5047
int Item_field::save_in_field(Field *to, bool no_conversions)
5050
if (result_field->is_null())
5053
res= set_field_to_null_with_conversions(to, no_conversions);
5058
res= field_conv(to,result_field);
5066
Store null in field.
5068
This is used on INSERT.
5069
Allow NULL to be inserted in timestamp and auto_increment values.
5071
@param field Field where we want to store NULL
5076
1 Field doesn't support NULL values and can't handle 'field = NULL'
5079
int Item_null::save_in_field(Field *field, bool no_conversions)
5081
return set_field_to_null_with_conversions(field, no_conversions);
5086
Store null in field.
5088
@param field Field where we want to store NULL
5093
1 Field doesn't support NULL values
5096
int Item_null::save_safe_in_field(Field *field)
5098
return set_field_to_null(field);
5103
This implementation can lose str_value content, so if the
5104
Item uses str_value to store something, it should
5105
reimplement it's ::save_in_field() as Item_string, for example, does.
5107
Note: all Item_XXX::val_str(str) methods must NOT rely on the fact that
5108
str != str_value. For example, see fix for bug #44743.
5111
int Item::save_in_field(Field *field, bool no_conversions)
5114
if (result_type() == STRING_RESULT ||
5115
(result_type() == REAL_RESULT &&
5116
field->result_type() == STRING_RESULT))
5119
CHARSET_INFO *cs= collation.collation;
5120
char buff[MAX_FIELD_WIDTH]; // Alloc buffer for small columns
5121
str_value.set_quick(buff, sizeof(buff), cs);
5122
result=val_str(&str_value);
5125
str_value.set_quick(0, 0, cs);
5126
return set_field_to_null_with_conversions(field, no_conversions);
5129
/* NOTE: If null_value == FALSE, "result" must be not NULL. */
5131
field->set_notnull();
5132
error=field->store(result->ptr(),result->length(),cs);
5133
str_value.set_quick(0, 0, cs);
5135
else if (result_type() == REAL_RESULT)
5137
double nr= val_real();
5139
return set_field_to_null(field);
5140
field->set_notnull();
5141
error=field->store(nr);
5143
else if (result_type() == DECIMAL_RESULT)
5145
my_decimal decimal_value;
5146
my_decimal *value= val_decimal(&decimal_value);
5148
return set_field_to_null_with_conversions(field, no_conversions);
5149
field->set_notnull();
5150
error=field->store_decimal(value);
5154
longlong nr=val_int();
5156
return set_field_to_null_with_conversions(field, no_conversions);
5157
field->set_notnull();
5158
error=field->store(nr, unsigned_flag);
5160
return error ? error : (field->table->in_use->is_error() ? 1 : 0);
5164
int Item_string::save_in_field(Field *field, bool no_conversions)
5167
result=val_str(&str_value);
5168
return save_str_value_in_field(field, result);
5172
int Item_uint::save_in_field(Field *field, bool no_conversions)
5174
/* Item_int::save_in_field handles both signed and unsigned. */
5175
return Item_int::save_in_field(field, no_conversions);
5178
static int save_int_value_in_field (Field *field, longlong nr,
5179
bool null_value, bool unsigned_flag)
5182
return set_field_to_null(field);
5183
field->set_notnull();
5184
return field->store(nr, unsigned_flag);
5188
int Item_int::save_in_field(Field *field, bool no_conversions)
5190
return save_int_value_in_field (field, val_int(), null_value, unsigned_flag);
5194
int Item_decimal::save_in_field(Field *field, bool no_conversions)
5196
field->set_notnull();
5197
return field->store_decimal(&decimal_value);
5201
bool Item_int::eq(const Item *arg, bool binary_cmp) const
5203
/* No need to check for null value as basic constant can't be NULL */
5204
if (arg->basic_const_item() && arg->type() == type())
5207
We need to cast off const to call val_int(). This should be OK for
5210
Item *item= (Item*) arg;
5211
return item->val_int() == value && item->unsigned_flag == unsigned_flag;
5217
Item *Item_int_with_ref::clone_item()
5219
DBUG_ASSERT(ref->const_item());
5221
We need to evaluate the constant to make sure it works with
5224
return (ref->unsigned_flag ?
5225
new Item_uint(ref->name, ref->val_int(), ref->max_length) :
5226
new Item_int(ref->name, ref->val_int(), ref->max_length));
5230
Item_num *Item_uint::neg()
5232
Item_decimal *item= new Item_decimal(value, 1);
5237
static uint nr_of_decimals(const char *str, const char *end)
5239
const char *decimal_point;
5241
/* Find position for '.' */
5246
if (*str == 'e' || *str == 'E')
5247
return NOT_FIXED_DEC;
5252
for (; my_isdigit(system_charset_info, *str) ; str++)
5254
if (*str == 'e' || *str == 'E')
5255
return NOT_FIXED_DEC;
5256
return (uint) (str - decimal_point);
5261
This function is only called during parsing. We will signal an error if
5262
value is not a true double value (overflow)
5265
Item_float::Item_float(const char *str_arg, uint length)
5269
value= my_strntod(&my_charset_bin, (char*) str_arg, length, &end_not_used,
5274
Note that we depend on that str_arg is null terminated, which is true
5275
when we are in the parser
5277
DBUG_ASSERT(str_arg[length] == 0);
5278
my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", (char*) str_arg);
5280
presentation= name=(char*) str_arg;
5281
decimals=(uint8) nr_of_decimals(str_arg, str_arg+length);
5287
int Item_float::save_in_field(Field *field, bool no_conversions)
5289
double nr= val_real();
5291
return set_field_to_null(field);
5292
field->set_notnull();
5293
return field->store(nr);
5297
void Item_float::print(String *str, enum_query_type query_type)
5301
str->append(presentation);
5305
String num(buffer, sizeof(buffer), &my_charset_bin);
5306
num.set_real(value, decimals, &my_charset_bin);
5313
In string context this is a binary string.
5314
In number context this is a longlong value.
5317
bool Item_float::eq(const Item *arg, bool binary_cmp) const
5319
if (arg->basic_const_item() && arg->type() == type())
5322
We need to cast off const to call val_int(). This should be OK for
5325
Item *item= (Item*) arg;
5326
return item->val_real() == value;
5332
inline uint char_val(char X)
5334
return (uint) (X >= '0' && X <= '9' ? X-'0' :
5335
X >= 'A' && X <= 'Z' ? X-'A'+10 :
5340
Item_hex_string::Item_hex_string(const char *str, uint str_length)
5342
max_length=(str_length+1)/2;
5343
char *ptr=(char*) sql_alloc(max_length+1);
5346
str_value.set(ptr,max_length,&my_charset_bin);
5347
char *end=ptr+max_length;
5348
if (max_length*2 != str_length)
5349
*ptr++=char_val(*str++); // Not even, assume 0 prefix
5352
*ptr++= (char) (char_val(str[0])*16+char_val(str[1]));
5355
*ptr=0; // Keep purify happy
5356
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
5361
longlong Item_hex_string::val_int()
5363
// following assert is redundant, because fixed=1 assigned in constructor
5364
DBUG_ASSERT(fixed == 1);
5365
char *end=(char*) str_value.ptr()+str_value.length(),
5366
*ptr=end-min(str_value.length(),sizeof(longlong));
5369
for (; ptr != end ; ptr++)
5370
value=(value << 8)+ (ulonglong) (uchar) *ptr;
5371
return (longlong) value;
5375
my_decimal *Item_hex_string::val_decimal(my_decimal *decimal_value)
5377
// following assert is redundant, because fixed=1 assigned in constructor
5378
DBUG_ASSERT(fixed == 1);
5379
ulonglong value= (ulonglong)val_int();
5380
int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value);
5381
return (decimal_value);
5385
int Item_hex_string::save_in_field(Field *field, bool no_conversions)
5387
field->set_notnull();
5388
if (field->result_type() == STRING_RESULT)
5389
return field->store(str_value.ptr(), str_value.length(),
5390
collation.collation);
5393
uint32 length= str_value.length();
5399
nr= field->flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX;
5402
nr= (ulonglong) val_int();
5403
if ((length == 8) && !(field->flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX))
5408
return field->store((longlong) nr, TRUE); // Assume hex numbers are unsigned
5411
if (!field->store((longlong) nr, TRUE))
5412
field->set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE,
5418
void Item_hex_string::print(String *str, enum_query_type query_type)
5420
char *end= (char*) str_value.ptr() + str_value.length(),
5421
*ptr= end - min(str_value.length(), sizeof(longlong));
5423
for (; ptr != end ; ptr++)
5425
str->append(_dig_vec_lower[((uchar) *ptr) >> 4]);
5426
str->append(_dig_vec_lower[((uchar) *ptr) & 0x0F]);
5431
bool Item_hex_string::eq(const Item *arg, bool binary_cmp) const
5433
if (arg->basic_const_item() && arg->type() == type())
5436
return !stringcmp(&str_value, &arg->str_value);
5437
return !sortcmp(&str_value, &arg->str_value, collation.collation);
5443
Item *Item_hex_string::safe_charset_converter(CHARSET_INFO *tocs)
5446
String tmp, *str= val_str(&tmp);
5448
if (!(conv= new Item_string(str->ptr(), str->length(), tocs)))
5450
conv->str_value.copy();
5451
conv->str_value.mark_as_const();
5458
In string context this is a binary string.
5459
In number context this is a longlong value.
5462
Item_bin_string::Item_bin_string(const char *str, uint str_length)
5464
const char *end= str + str_length - 1;
5468
max_length= (str_length + 7) >> 3;
5469
char *ptr= (char*) sql_alloc(max_length + 1);
5472
str_value.set(ptr, max_length, &my_charset_bin);
5476
ptr+= max_length - 1;
5477
ptr[1]= 0; // Set end null for string
5478
for (; end >= str; end--)
5495
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
5501
Pack data in buffer for sending.
5504
bool Item_null::send(Protocol *protocol, String *packet)
5506
return protocol->store_null();
5510
This is only called from items that is not of type item_field.
5513
bool Item::send(Protocol *protocol, String *buffer)
5515
bool UNINIT_VAR(result); // Will be set if null_value == 0
5516
enum_field_types f_type;
5518
switch ((f_type=field_type())) {
5520
case MYSQL_TYPE_NULL:
5521
case MYSQL_TYPE_DECIMAL:
5522
case MYSQL_TYPE_ENUM:
5523
case MYSQL_TYPE_SET:
5524
case MYSQL_TYPE_TINY_BLOB:
5525
case MYSQL_TYPE_MEDIUM_BLOB:
5526
case MYSQL_TYPE_LONG_BLOB:
5527
case MYSQL_TYPE_BLOB:
5528
case MYSQL_TYPE_GEOMETRY:
5529
case MYSQL_TYPE_STRING:
5530
case MYSQL_TYPE_VAR_STRING:
5531
case MYSQL_TYPE_VARCHAR:
5532
case MYSQL_TYPE_BIT:
5533
case MYSQL_TYPE_NEWDECIMAL:
5536
if ((res=val_str(buffer)))
5537
result= protocol->store(res->ptr(),res->length(),res->charset());
5540
case MYSQL_TYPE_TINY:
5545
result= protocol->store_tiny(nr);
5548
case MYSQL_TYPE_SHORT:
5549
case MYSQL_TYPE_YEAR:
5554
result= protocol->store_short(nr);
5557
case MYSQL_TYPE_INT24:
5558
case MYSQL_TYPE_LONG:
5563
result= protocol->store_long(nr);
5566
case MYSQL_TYPE_LONGLONG:
5571
result= protocol->store_longlong(nr, unsigned_flag);
5574
case MYSQL_TYPE_FLOAT:
5577
nr= (float) val_real();
5579
result= protocol->store(nr, decimals, buffer);
5582
case MYSQL_TYPE_DOUBLE:
5584
double nr= val_real();
5586
result= protocol->store(nr, decimals, buffer);
5589
case MYSQL_TYPE_DATETIME:
5590
case MYSQL_TYPE_DATE:
5591
case MYSQL_TYPE_TIMESTAMP:
5594
get_date(&tm, TIME_FUZZY_DATE);
5597
if (f_type == MYSQL_TYPE_DATE)
5598
return protocol->store_date(&tm);
5600
result= protocol->store(&tm);
5604
case MYSQL_TYPE_TIME:
5609
result= protocol->store_time(&tm);
5614
result= protocol->store_null();
5619
bool Item_field::send(Protocol *protocol, String *buffer)
5621
return protocol->store(result_field);
5625
void Item_field::update_null_value()
5628
need to set no_errors to prevent warnings about type conversion
5631
THD *thd= field->table->in_use;
5634
no_errors= thd->no_errors;
5636
Item::update_null_value();
5637
thd->no_errors= no_errors;
5642
Add the field to the select list and substitute it for the reference to
5646
Item_field::update_value_transformer()
5647
select_arg current select
5650
If the field doesn't belong to the table being inserted into then it is
5651
added to the select list, pointer to it is stored in the ref_pointer_array
5652
of the select and the field itself is substituted for the Item_ref object.
5653
This is done in order to get correct values from update fields that
5654
belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY
5659
ref if all conditions are met
5660
this field otherwise
5663
Item *Item_field::update_value_transformer(uchar *select_arg)
5665
SELECT_LEX *select= (SELECT_LEX*)select_arg;
5668
if (field->table != select->context.table_list->table &&
5669
type() != Item::TRIGGER_FIELD_ITEM)
5671
List<Item> *all_fields= &select->join->all_fields;
5672
Item **ref_pointer_array= select->ref_pointer_array;
5673
int el= all_fields->elements;
5676
ref_pointer_array[el]= (Item*)this;
5677
all_fields->push_front((Item*)this);
5678
ref= new Item_ref(&select->context, ref_pointer_array + el,
5679
table_name, field_name);
5686
void Item_field::print(String *str, enum_query_type query_type)
5688
if (field && field->table->const_table)
5690
char buff[MAX_FIELD_WIDTH];
5691
String tmp(buff,sizeof(buff),str->charset());
5692
field->val_str(&tmp);
5698
Item_ident::print(str, query_type);
5702
Item_ref::Item_ref(Name_resolution_context *context_arg,
5703
Item **item, const char *table_name_arg,
5704
const char *field_name_arg,
5705
bool alias_name_used_arg)
5706
:Item_ident(context_arg, NullS, table_name_arg, field_name_arg),
5707
result_field(0), ref(item)
5709
alias_name_used= alias_name_used_arg;
5711
This constructor used to create some internals references over fixed items
5713
if (ref && *ref && (*ref)->fixed)
5719
Resolve the name of a reference to a column reference.
5721
The method resolves the column reference represented by 'this' as a column
5722
present in one of: GROUP BY clause, SELECT clause, outer queries. It is
5723
used typically for columns in the HAVING clause which are not under
5724
aggregate functions.
5727
Item_ref::ref is 0 or points to a valid item.
5730
The name resolution algorithm used is (where [T_j] is an optional table
5731
name that qualifies the column name):
5734
resolve_extended([T_j].col_ref_i)
5736
Search for a column or derived column named col_ref_i [in table T_j]
5737
in the SELECT and GROUP clauses of Q.
5739
if such a column is NOT found AND // Lookup in outer queries.
5740
there are outer queries
5742
for each outer query Q_k beginning from the inner-most one
5744
Search for a column or derived column named col_ref_i
5745
[in table T_j] in the SELECT and GROUP clauses of Q_k.
5747
if such a column is not found AND
5748
- Q_k is not a group query AND
5749
- Q_k is not inside an aggregate function
5751
- Q_(k-1) is not in a HAVING or SELECT clause of Q_k
5753
search for a column or derived column named col_ref_i
5754
[in table T_j] in the FROM clause of Q_k;
5761
This procedure treats GROUP BY and SELECT clauses as one namespace for
5762
column references in HAVING. Notice that compared to
5763
Item_field::fix_fields, here we first search the SELECT and GROUP BY
5764
clauses, and then we search the FROM clause.
5766
@param[in] thd current thread
5767
@param[in,out] reference view column if this item was resolved to a
5771
Here we could first find the field anyway, and then test this
5772
condition, so that we can give a better error message -
5773
ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
5774
ER_BAD_FIELD_ERROR which we produce now.
5782
bool Item_ref::fix_fields(THD *thd, Item **reference)
5784
enum_parsing_place place= NO_MATTER;
5785
DBUG_ASSERT(fixed == 0);
5786
SELECT_LEX *current_sel= thd->lex->current_select;
5788
if (!ref || ref == not_found_item)
5790
if (!(ref= resolve_ref_in_select_and_group(thd, this,
5791
context->select_lex)))
5792
goto error; /* Some error occurred (e.g. ambiguous names). */
5794
if (ref == not_found_item) /* This reference was not resolved. */
5796
Name_resolution_context *last_checked_context= context;
5797
Name_resolution_context *outer_context= context->outer_context;
5803
/* The current reference cannot be resolved in this query. */
5804
my_error(ER_BAD_FIELD_ERROR,MYF(0),
5805
this->full_name(), current_thd->where);
5810
If there is an outer context (select), and it is not a derived table
5811
(which do not support the use of outer fields for now), try to
5812
resolve this reference in the outer select(s).
5814
We treat each subselect as a separate namespace, so that different
5815
subselects may contain columns with the same names. The subselects are
5816
searched starting from the innermost.
5818
from_field= (Field*) not_found_field;
5822
SELECT_LEX *select= outer_context->select_lex;
5823
Item_subselect *prev_subselect_item=
5824
last_checked_context->select_lex->master_unit()->item;
5825
last_checked_context= outer_context;
5827
/* Search in the SELECT and GROUP lists of the outer select. */
5828
if (outer_context->resolve_in_select_list)
5830
if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
5831
goto error; /* Some error occurred (e.g. ambiguous names). */
5832
if (ref != not_found_item)
5834
DBUG_ASSERT(*ref && (*ref)->fixed);
5835
prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
5836
prev_subselect_item->const_item_cache&= (*ref)->const_item();
5840
Set ref to 0 to ensure that we get an error in case we replaced
5841
this item with another item and still use this item in some
5842
other place of the parse tree.
5847
place= prev_subselect_item->parsing_place;
5849
Check table fields only if the subquery is used somewhere out of
5850
HAVING or the outer SELECT does not use grouping (i.e. tables are
5853
Here we could first find the field anyway, and then test this
5854
condition, so that we can give a better error message -
5855
ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
5856
ER_BAD_FIELD_ERROR which we produce now.
5858
if ((place != IN_HAVING ||
5859
(!select->with_sum_func &&
5860
select->group_list.elements == 0)))
5863
In case of view, find_field_in_tables() write pointer to view
5864
field expression to 'reference', i.e. it substitute that
5865
expression instead of this Item_ref
5867
from_field= find_field_in_tables(thd, this,
5869
first_name_resolution_table,
5871
last_name_resolution_table,
5873
IGNORE_EXCEPT_NON_UNIQUE,
5877
if (from_field == view_ref_found)
5879
Item::Type refer_type= (*reference)->type();
5880
prev_subselect_item->used_tables_cache|=
5881
(*reference)->used_tables();
5882
prev_subselect_item->const_item_cache&=
5883
(*reference)->const_item();
5884
DBUG_ASSERT((*reference)->type() == REF_ITEM);
5885
mark_as_dependent(thd, last_checked_context->select_lex,
5886
context->select_lex, this,
5887
((refer_type == REF_ITEM ||
5888
refer_type == FIELD_ITEM) ?
5889
(Item_ident*) (*reference) :
5892
view reference found, we substituted it instead of this
5897
if (from_field != not_found_field)
5899
if (cached_table && cached_table->select_lex &&
5900
outer_context->select_lex &&
5901
cached_table->select_lex != outer_context->select_lex)
5904
Due to cache, find_field_in_tables() can return field which
5905
doesn't belong to provided outer_context. In this case we have
5906
to find proper field context in order to fix field correcly.
5910
outer_context= outer_context->outer_context;
5911
select= outer_context->select_lex;
5912
prev_subselect_item=
5913
last_checked_context->select_lex->master_unit()->item;
5914
last_checked_context= outer_context;
5915
} while (outer_context && outer_context->select_lex &&
5916
cached_table->select_lex != outer_context->select_lex);
5918
prev_subselect_item->used_tables_cache|= from_field->table->map;
5919
prev_subselect_item->const_item_cache= 0;
5923
DBUG_ASSERT(from_field == not_found_field);
5925
/* Reference is not found => depend on outer (or just error). */
5926
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
5927
prev_subselect_item->const_item_cache= 0;
5929
outer_context= outer_context->outer_context;
5930
} while (outer_context);
5932
DBUG_ASSERT(from_field != 0 && from_field != view_ref_found);
5933
if (from_field != not_found_field)
5936
if (!(fld= new Item_field(from_field)))
5938
thd->change_item_tree(reference, fld);
5939
mark_as_dependent(thd, last_checked_context->select_lex,
5940
thd->lex->current_select, this, fld);
5942
A reference is resolved to a nest level that's outer or the same as
5943
the nest level of the enclosing set function : adjust the value of
5944
max_arg_level for the function if it's needed.
5946
if (thd->lex->in_sum_func &&
5947
thd->lex->in_sum_func->nest_level >=
5948
last_checked_context->select_lex->nest_level)
5949
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5950
last_checked_context->select_lex->nest_level);
5955
/* The item was not a table field and not a reference */
5956
my_error(ER_BAD_FIELD_ERROR, MYF(0),
5957
this->full_name(), current_thd->where);
5960
/* Should be checked in resolve_ref_in_select_and_group(). */
5961
DBUG_ASSERT(*ref && (*ref)->fixed);
5962
mark_as_dependent(thd, last_checked_context->select_lex,
5963
context->select_lex, this, this);
5965
A reference is resolved to a nest level that's outer or the same as
5966
the nest level of the enclosing set function : adjust the value of
5967
max_arg_level for the function if it's needed.
5969
if (thd->lex->in_sum_func &&
5970
thd->lex->in_sum_func->nest_level >=
5971
last_checked_context->select_lex->nest_level)
5972
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5973
last_checked_context->select_lex->nest_level);
5979
Check if this is an incorrect reference in a group function or forward
5980
reference. Do not issue an error if this is:
5981
1. outer reference (will be fixed later by the fix_inner_refs function);
5982
2. an unnamed reference inside an aggregate function.
5984
if (!((*ref)->type() == REF_ITEM &&
5985
((Item_ref *)(*ref))->ref_type() == OUTER_REF) &&
5986
(((*ref)->with_sum_func && name &&
5987
!(current_sel->linkage != GLOBAL_OPTIONS_TYPE &&
5988
current_sel->having_fix_field)) ||
5991
my_error(ER_ILLEGAL_REFERENCE, MYF(0),
5992
name, ((*ref)->with_sum_func?
5993
"reference to group function":
5994
"forward reference in item list"));
6000
if ((*ref)->check_cols(1))
6005
context->process_error(thd);
6010
void Item_ref::set_properties()
6012
max_length= (*ref)->max_length;
6013
maybe_null= (*ref)->maybe_null;
6014
decimals= (*ref)->decimals;
6015
collation.set((*ref)->collation);
6017
We have to remember if we refer to a sum function, to ensure that
6018
split_sum_func() doesn't try to change the reference.
6020
with_sum_func= (*ref)->with_sum_func;
6021
unsigned_flag= (*ref)->unsigned_flag;
6023
if (alias_name_used)
6025
if ((*ref)->type() == FIELD_ITEM)
6026
alias_name_used= ((Item_ident *) (*ref))->alias_name_used;
6028
alias_name_used= TRUE; // it is not field, so it is was resolved by alias
6032
void Item_ref::cleanup()
6034
DBUG_ENTER("Item_ref::cleanup");
6035
Item_ident::cleanup();
6041
void Item_ref::print(String *str, enum_query_type query_type)
6045
if ((*ref)->type() != Item::CACHE_ITEM && ref_type() != VIEW_REF &&
6046
!table_name && name && alias_name_used)
6048
THD *thd= current_thd;
6049
append_identifier(thd, str, (*ref)->real_item()->name,
6050
(*ref)->real_item()->name_length);
6053
(*ref)->print(str, query_type);
6056
Item_ident::print(str, query_type);
6060
bool Item_ref::send(Protocol *prot, String *tmp)
6063
return prot->store(result_field);
6064
return (*ref)->send(prot, tmp);
6068
double Item_ref::val_result()
6072
if ((null_value= result_field->is_null()))
6074
return result_field->val_real();
6080
bool Item_ref::is_null_result()
6083
return (null_value=result_field->is_null());
6089
longlong Item_ref::val_int_result()
6093
if ((null_value= result_field->is_null()))
6095
return result_field->val_int();
6101
String *Item_ref::str_result(String* str)
6105
if ((null_value= result_field->is_null()))
6107
str->set_charset(str_value.charset());
6108
return result_field->val_str(str, &str_value);
6110
return val_str(str);
6114
my_decimal *Item_ref::val_decimal_result(my_decimal *decimal_value)
6118
if ((null_value= result_field->is_null()))
6120
return result_field->val_decimal(decimal_value);
6122
return val_decimal(decimal_value);
6126
bool Item_ref::val_bool_result()
6130
if ((null_value= result_field->is_null()))
6132
switch (result_field->result_type()) {
6134
return result_field->val_int() != 0;
6135
case DECIMAL_RESULT:
6137
my_decimal decimal_value;
6138
my_decimal *val= result_field->val_decimal(&decimal_value);
6140
return !my_decimal_is_zero(val);
6145
return result_field->val_real() != 0.0;
6155
double Item_ref::val_real()
6158
double tmp=(*ref)->val_result();
6159
null_value=(*ref)->null_value;
6164
longlong Item_ref::val_int()
6167
longlong tmp=(*ref)->val_int_result();
6168
null_value=(*ref)->null_value;
6173
bool Item_ref::val_bool()
6176
bool tmp= (*ref)->val_bool_result();
6177
null_value= (*ref)->null_value;
6182
String *Item_ref::val_str(String* tmp)
6185
tmp=(*ref)->str_result(tmp);
6186
null_value=(*ref)->null_value;
6191
bool Item_ref::is_null()
6194
bool tmp=(*ref)->is_null_result();
6195
null_value=(*ref)->null_value;
6200
bool Item_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
6202
return (null_value=(*ref)->get_date_result(ltime,fuzzydate));
6206
my_decimal *Item_ref::val_decimal(my_decimal *decimal_value)
6208
my_decimal *val= (*ref)->val_decimal_result(decimal_value);
6209
null_value= (*ref)->null_value;
6213
int Item_ref::save_in_field(Field *to, bool no_conversions)
6216
DBUG_ASSERT(!result_field);
6217
res= (*ref)->save_in_field(to, no_conversions);
6218
null_value= (*ref)->null_value;
6223
void Item_ref::save_org_in_field(Field *field)
6225
(*ref)->save_org_in_field(field);
6229
void Item_ref::make_field(Send_field *field)
6231
(*ref)->make_field(field);
6232
/* Non-zero in case of a view */
6234
field->col_name= name;
6236
field->table_name= table_name;
6238
field->db_name= db_name;
6239
if (orig_field_name)
6240
field->org_col_name= orig_field_name;
6241
if (orig_table_name)
6242
field->org_table_name= orig_table_name;
6246
Item *Item_ref::get_tmp_table_item(THD *thd)
6249
return (*ref)->get_tmp_table_item(thd);
6251
Item_field *item= new Item_field(result_field);
6254
item->table_name= table_name;
6255
item->db_name= db_name;
6261
void Item_ref_null_helper::print(String *str, enum_query_type query_type)
6263
str->append(STRING_WITH_LEN("<ref_null_helper>("));
6265
(*ref)->print(str, query_type);
6272
double Item_direct_ref::val_real()
6274
double tmp=(*ref)->val_real();
6275
null_value=(*ref)->null_value;
6280
longlong Item_direct_ref::val_int()
6282
longlong tmp=(*ref)->val_int();
6283
null_value=(*ref)->null_value;
6288
String *Item_direct_ref::val_str(String* tmp)
6290
tmp=(*ref)->val_str(tmp);
6291
null_value=(*ref)->null_value;
6296
my_decimal *Item_direct_ref::val_decimal(my_decimal *decimal_value)
6298
my_decimal *tmp= (*ref)->val_decimal(decimal_value);
6299
null_value=(*ref)->null_value;
6304
bool Item_direct_ref::val_bool()
6306
bool tmp= (*ref)->val_bool();
6307
null_value=(*ref)->null_value;
6312
bool Item_direct_ref::is_null()
6314
return (*ref)->is_null();
6318
bool Item_direct_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
6320
return (null_value=(*ref)->get_date(ltime,fuzzydate));
6325
Prepare referenced field then call usual Item_direct_ref::fix_fields .
6327
@param thd thread handler
6328
@param reference reference on reference where this item stored
6336
bool Item_direct_view_ref::fix_fields(THD *thd, Item **reference)
6338
/* view fild reference must be defined */
6340
/* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */
6343
Item *ref_item= (*ref)->real_item();
6344
if (ref_item->type() == Item::FIELD_ITEM)
6347
In some cases we need to update table read set(see bug#47150).
6348
If ref item is FIELD_ITEM and fixed then field and table
6349
have proper values. So we can use them for update.
6351
Field *fld= ((Item_field*) ref_item)->field;
6352
DBUG_ASSERT(fld && fld->table);
6353
if (thd->mark_used_columns == MARK_COLUMNS_READ)
6354
bitmap_set_bit(fld->table->read_set, fld->field_index);
6357
else if (!(*ref)->fixed &&
6358
((*ref)->fix_fields(thd, ref)))
6361
return Item_direct_ref::fix_fields(thd, reference);
6365
Prepare referenced outer field then call usual Item_direct_ref::fix_fields
6368
Item_outer_ref::fix_fields()
6370
reference reference on reference where this item stored
6377
bool Item_outer_ref::fix_fields(THD *thd, Item **reference)
6380
/* outer_ref->check_cols() will be made in Item_direct_ref::fix_fields */
6381
if ((*ref) && !(*ref)->fixed && ((*ref)->fix_fields(thd, reference)))
6383
err= Item_direct_ref::fix_fields(thd, reference);
6386
if ((*ref)->type() == Item::FIELD_ITEM)
6387
table_name= ((Item_field*)outer_ref)->table_name;
6393
Compare two view column references for equality.
6395
A view column reference is considered equal to another column
6396
reference if the second one is a view column and if both column
6397
references resolve to the same item. It is assumed that both
6398
items are of the same type.
6400
@param item item to compare with
6401
@param binary_cmp make binary comparison
6404
TRUE Referenced item is equal to given item
6409
bool Item_direct_view_ref::eq(const Item *item, bool binary_cmp) const
6411
if (item->type() == REF_ITEM)
6413
Item_ref *item_ref= (Item_ref*) item;
6414
if (item_ref->ref_type() == VIEW_REF)
6416
Item *item_ref_ref= *(item_ref->ref);
6417
return ((*ref)->real_item() == item_ref_ref->real_item());
6423
bool Item_default_value::eq(const Item *item, bool binary_cmp) const
6425
return item->type() == DEFAULT_VALUE_ITEM &&
6426
((Item_default_value *)item)->arg->eq(arg, binary_cmp);
6430
bool Item_default_value::fix_fields(THD *thd, Item **items)
6433
Item_field *field_arg;
6435
DBUG_ASSERT(fixed == 0);
6442
if (!arg->fixed && arg->fix_fields(thd, &arg))
6446
real_arg= arg->real_item();
6447
if (real_arg->type() != FIELD_ITEM)
6449
my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->name);
6453
field_arg= (Item_field *)real_arg;
6454
if (field_arg->field->flags & NO_DEFAULT_VALUE_FLAG)
6456
my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), field_arg->field->field_name);
6459
if (!(def_field= (Field*) sql_alloc(field_arg->field->size_of())))
6461
memcpy(def_field, field_arg->field, field_arg->field->size_of());
6462
def_field->move_field_offset((my_ptrdiff_t)
6463
(def_field->table->s->default_values -
6464
def_field->table->record[0]));
6465
set_field(def_field);
6469
context->process_error(thd);
6474
void Item_default_value::print(String *str, enum_query_type query_type)
6478
str->append(STRING_WITH_LEN("default"));
6481
str->append(STRING_WITH_LEN("default("));
6482
arg->print(str, query_type);
6487
int Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
6491
if (field_arg->flags & NO_DEFAULT_VALUE_FLAG &&
6492
field_arg->real_type() != MYSQL_TYPE_ENUM)
6494
if (field_arg->reset())
6496
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
6497
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
6501
if (context->error_processor == &view_error_processor)
6503
TABLE_LIST *view= cached_table->top_table();
6504
push_warning_printf(field_arg->table->in_use,
6505
MYSQL_ERROR::WARN_LEVEL_WARN,
6506
ER_NO_DEFAULT_FOR_VIEW_FIELD,
6507
ER(ER_NO_DEFAULT_FOR_VIEW_FIELD),
6509
view->view_name.str);
6513
push_warning_printf(field_arg->table->in_use,
6514
MYSQL_ERROR::WARN_LEVEL_WARN,
6515
ER_NO_DEFAULT_FOR_FIELD,
6516
ER(ER_NO_DEFAULT_FOR_FIELD),
6517
field_arg->field_name);
6521
field_arg->set_default();
6524
return Item_field::save_in_field(field_arg, no_conversions);
6529
This method like the walk method traverses the item tree, but at the
6530
same time it can replace some nodes in the tree.
6533
Item *Item_default_value::transform(Item_transformer transformer, uchar *args)
6535
DBUG_ASSERT(!current_thd->is_stmt_prepare());
6538
If the value of arg is NULL, then this object represents a constant,
6539
so further transformation is unnecessary (and impossible).
6544
Item *new_item= arg->transform(transformer, args);
6549
THD::change_item_tree() should be called only if the tree was
6550
really transformed, i.e. when a new item has been created.
6551
Otherwise we'll be allocating a lot of unnecessary memory for
6552
change records at each execution.
6554
if (arg != new_item)
6555
current_thd->change_item_tree(&arg, new_item);
6556
return (this->*transformer)(args);
6560
bool Item_insert_value::eq(const Item *item, bool binary_cmp) const
6562
return item->type() == INSERT_VALUE_ITEM &&
6563
((Item_default_value *)item)->arg->eq(arg, binary_cmp);
6567
bool Item_insert_value::fix_fields(THD *thd, Item **items)
6569
DBUG_ASSERT(fixed == 0);
6570
/* We should only check that arg is in first table */
6574
TABLE_LIST *orig_next_table= context->last_name_resolution_table;
6575
context->last_name_resolution_table= context->first_name_resolution_table;
6576
res= arg->fix_fields(thd, &arg);
6577
context->last_name_resolution_table= orig_next_table;
6582
if (arg->type() == REF_ITEM)
6584
Item_ref *ref= (Item_ref *)arg;
6585
if (ref->ref[0]->type() != FIELD_ITEM)
6587
my_error(ER_BAD_FIELD_ERROR, MYF(0), "", "VALUES() function");
6593
According to our SQL grammar, VALUES() function can reference
6596
DBUG_ASSERT(arg->type() == FIELD_ITEM);
6598
Item_field *field_arg= (Item_field *)arg;
6600
if (field_arg->field->table->insert_values)
6602
Field *def_field= (Field*) sql_alloc(field_arg->field->size_of());
6605
memcpy(def_field, field_arg->field, field_arg->field->size_of());
6606
def_field->move_field_offset((my_ptrdiff_t)
6607
(def_field->table->insert_values -
6608
def_field->table->record[0]));
6609
set_field(def_field);
6613
Field *tmp_field= field_arg->field;
6614
/* charset doesn't matter here, it's to avoid sigsegv only */
6615
tmp_field= new Field_null(0, 0, Field::NONE, field_arg->field->field_name,
6619
tmp_field->init(field_arg->field->table);
6620
set_field(tmp_field);
6626
void Item_insert_value::print(String *str, enum_query_type query_type)
6628
str->append(STRING_WITH_LEN("values("));
6629
arg->print(str, query_type);
6635
Find index of Field object which will be appropriate for item
6636
representing field of row being changed in trigger.
6638
@param thd current thread context
6639
@param table table of trigger (and where we looking for fields)
6640
@param table_grant_info GRANT_INFO of the subject table
6643
This function does almost the same as fix_fields() for Item_field
6644
but is invoked right after trigger definition parsing. Since at
6645
this stage we can't say exactly what Field object (corresponding
6646
to TABLE::record[0] or TABLE::record[1]) should be bound to this
6647
Item, we only find out index of the Field and then select concrete
6648
Field object in fix_fields() (by that time Table_trigger_list::old_field/
6649
new_field should point to proper array of Fields).
6650
It also binds Item_trigger_field to Table_triggers_list object for
6651
table of trigger which uses this item.
6654
void Item_trigger_field::setup_field(THD *thd, TABLE *table,
6655
GRANT_INFO *table_grant_info)
6658
It is too early to mark fields used here, because before execution
6659
of statement that will invoke trigger other statements may use same
6660
TABLE object, so all such mark-up will be wiped out.
6661
So instead we do it in Table_triggers_list::mark_fields_used()
6662
method which is called during execution of these statements.
6664
enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
6665
thd->mark_used_columns= MARK_COLUMNS_NONE;
6667
Try to find field by its name and if it will be found
6668
set field_idx properly.
6670
(void)find_field_in_table(thd, table, field_name, (uint) strlen(field_name),
6672
thd->mark_used_columns= save_mark_used_columns;
6673
triggers= table->triggers;
6674
table_grants= table_grant_info;
6678
bool Item_trigger_field::eq(const Item *item, bool binary_cmp) const
6680
return item->type() == TRIGGER_FIELD_ITEM &&
6681
row_version == ((Item_trigger_field *)item)->row_version &&
6682
!my_strcasecmp(system_charset_info, field_name,
6683
((Item_trigger_field *)item)->field_name);
6687
void Item_trigger_field::set_required_privilege(bool rw)
6690
Require SELECT and UPDATE privilege if this field will be read and
6691
set, and only UPDATE privilege for setting the field.
6693
want_privilege= (rw ? SELECT_ACL | UPDATE_ACL : UPDATE_ACL);
6697
bool Item_trigger_field::set_value(THD *thd, sp_rcontext * /*ctx*/, Item **it)
6699
Item *item= sp_prepare_func_item(thd, it);
6701
return (!item || (!fixed && fix_fields(thd, 0)) ||
6702
(item->save_in_field(field, 0) < 0));
6706
bool Item_trigger_field::fix_fields(THD *thd, Item **items)
6709
Since trigger is object tightly associated with TABLE object most
6710
of its set up can be performed during trigger loading i.e. trigger
6711
parsing! So we have little to do in fix_fields. :)
6714
DBUG_ASSERT(fixed == 0);
6718
if (field_idx != (uint)-1)
6720
#ifndef NO_EMBEDDED_ACCESS_CHECKS
6722
Check access privileges for the subject table. We check privileges only
6728
table_grants->want_privilege= want_privilege;
6730
if (check_grant_column(thd, table_grants, triggers->trigger_table->s->db.str,
6731
triggers->trigger_table->s->table_name.str, field_name,
6732
strlen(field_name), thd->security_ctx))
6735
#endif // NO_EMBEDDED_ACCESS_CHECKS
6737
field= (row_version == OLD_ROW) ? triggers->old_field[field_idx] :
6738
triggers->new_field[field_idx];
6744
my_error(ER_BAD_FIELD_ERROR, MYF(0), field_name,
6745
(row_version == NEW_ROW) ? "NEW" : "OLD");
6750
void Item_trigger_field::print(String *str, enum_query_type query_type)
6752
str->append((row_version == NEW_ROW) ? "NEW" : "OLD", 3);
6754
str->append(field_name);
6758
void Item_trigger_field::cleanup()
6760
want_privilege= original_privilege;
6762
Since special nature of Item_trigger_field we should not do most of
6763
things from Item_field::cleanup() or Item_ident::cleanup() here.
6769
Item_result item_cmp_type(Item_result a,Item_result b)
6771
if (a == STRING_RESULT && b == STRING_RESULT)
6772
return STRING_RESULT;
6773
if (a == INT_RESULT && b == INT_RESULT)
6775
else if (a == ROW_RESULT || b == ROW_RESULT)
6777
if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
6778
(b == INT_RESULT || b == DECIMAL_RESULT))
6779
return DECIMAL_RESULT;
6784
void resolve_const_item(THD *thd, Item **ref, Item *comp_item)
6787
Item *new_item= NULL;
6788
if (item->basic_const_item())
6789
return; // Can't be better
6790
Item_result res_type=item_cmp_type(comp_item->result_type(),
6791
item->result_type());
6792
char *name=item->name; // Alloced by sql_alloc
6797
char buff[MAX_FIELD_WIDTH];
6798
String tmp(buff,sizeof(buff),&my_charset_bin),*result;
6799
result=item->val_str(&tmp);
6800
if (item->null_value)
6801
new_item= new Item_null(name);
6804
uint length= result->length();
6805
char *tmp_str= sql_strmake(result->ptr(), length);
6806
new_item= new Item_string(name, tmp_str, length, result->charset());
6812
longlong result=item->val_int();
6813
uint length=item->max_length;
6814
bool null_value=item->null_value;
6815
new_item= (null_value ? (Item*) new Item_null(name) :
6816
(Item*) new Item_int(name, result, length));
6820
if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
6823
Substitute constants only in Item_rows. Don't affect other Items
6824
with ROW_RESULT (eg Item_singlerow_subselect).
6826
For such Items more optimal is to detect if it is constant and replace
6827
it with Item_row. This would optimize queries like this:
6828
SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
6830
Item_row *item_row= (Item_row*) item;
6831
Item_row *comp_item_row= (Item_row*) comp_item;
6835
If item and comp_item are both Item_rows and have same number of cols
6836
then process items in Item_row one by one.
6837
We can't ignore NULL values here as this item may be used with <=>, in
6838
which case NULL's are significant.
6840
DBUG_ASSERT(item->result_type() == comp_item->result_type());
6841
DBUG_ASSERT(item_row->cols() == comp_item_row->cols());
6842
col= item_row->cols();
6844
resolve_const_item(thd, item_row->addr(col),
6845
comp_item_row->element_index(col));
6850
{ // It must REAL_RESULT
6851
double result= item->val_real();
6852
uint length=item->max_length,decimals=item->decimals;
6853
bool null_value=item->null_value;
6854
new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
6855
new Item_float(name, result, decimals, length));
6858
case DECIMAL_RESULT:
6860
my_decimal decimal_value;
6861
my_decimal *result= item->val_decimal(&decimal_value);
6862
uint length= item->max_length, decimals= item->decimals;
6863
bool null_value= item->null_value;
6864
new_item= (null_value ?
6865
(Item*) new Item_null(name) :
6866
(Item*) new Item_decimal(name, result, length, decimals));
6873
thd->change_item_tree(ref, new_item);
6877
Compare the value stored in field with the expression from the query.
6879
@param field Field which the Item is stored in after conversion
6880
@param item Original expression from query
6882
@return Returns an integer greater than, equal to, or less than 0 if
6883
the value stored in the field is greater than, equal to,
6884
or less than the original Item. A 0 may also be returned if
6887
@note We only use this on the range optimizer/partition pruning,
6888
because in some cases we can't store the value in the field
6889
without some precision/character loss.
6892
int stored_field_cmp_to_item(THD *thd, Field *field, Item *item)
6894
Item_result res_type=item_cmp_type(field->result_type(),
6895
item->result_type());
6896
if (res_type == STRING_RESULT)
6898
char item_buff[MAX_FIELD_WIDTH];
6899
char field_buff[MAX_FIELD_WIDTH];
6901
String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin);
6902
String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
6903
String *item_result= item->val_str(&item_tmp);
6905
Some implementations of Item::val_str(String*) actually modify
6906
the field Item::null_value, hence we can't check it earlier.
6908
if (item->null_value)
6910
String *field_result= field->val_str(&field_tmp);
6912
enum_field_types field_type= field->type();
6914
if (field_type == MYSQL_TYPE_DATE || field_type == MYSQL_TYPE_DATETIME)
6916
enum_mysql_timestamp_type type= MYSQL_TIMESTAMP_ERROR;
6918
if (field_type == MYSQL_TYPE_DATE)
6919
type= MYSQL_TIMESTAMP_DATE;
6921
if (field_type == MYSQL_TYPE_DATETIME)
6922
type= MYSQL_TIMESTAMP_DATETIME;
6924
const char *field_name= field->field_name;
6925
MYSQL_TIME field_time, item_time;
6926
get_mysql_time_from_str(thd, field_result, type, field_name, &field_time);
6927
get_mysql_time_from_str(thd, item_result, type, field_name, &item_time);
6929
return my_time_compare(&field_time, &item_time);
6931
return stringcmp(field_result, item_result);
6933
if (res_type == INT_RESULT)
6934
return 0; // Both are of type int
6935
if (res_type == DECIMAL_RESULT)
6937
my_decimal item_buf, *item_val,
6938
field_buf, *field_val;
6939
item_val= item->val_decimal(&item_buf);
6940
if (item->null_value)
6942
field_val= field->val_decimal(&field_buf);
6943
return my_decimal_cmp(item_val, field_val);
6945
double result= item->val_real();
6946
if (item->null_value)
6948
double field_result= field->val_real();
6949
if (field_result < result)
6951
else if (field_result > result)
6956
Item_cache* Item_cache::get_cache(const Item *item)
6958
return get_cache(item, item->result_type());
6963
Get a cache item of given type.
6965
@param item value to be cached
6966
@param type required type of cache
6971
Item_cache* Item_cache::get_cache(const Item *item, const Item_result type)
6975
return new Item_cache_int(item->field_type());
6977
return new Item_cache_real();
6978
case DECIMAL_RESULT:
6979
return new Item_cache_decimal();
6981
return new Item_cache_str(item);
6983
return new Item_cache_row();
6985
// should never be in real life
6991
void Item_cache::store(Item *item)
6996
value_cached= FALSE;
6999
void Item_cache::print(String *str, enum_query_type query_type)
7001
str->append(STRING_WITH_LEN("<cache>("));
7003
example->print(str, query_type);
7005
Item::print(str, query_type);
7009
bool Item_cache_int::cache_value()
7014
value= example->val_int_result();
7015
null_value= example->null_value;
7016
unsigned_flag= example->unsigned_flag;
7021
void Item_cache_int::store(Item *item, longlong val_arg)
7023
/* An explicit values is given, save it. */
7026
null_value= item->null_value;
7027
unsigned_flag= item->unsigned_flag;
7031
String *Item_cache_int::val_str(String *str)
7033
DBUG_ASSERT(fixed == 1);
7034
if (!value_cached && !cache_value())
7036
str->set(value, default_charset());
7041
my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val)
7043
DBUG_ASSERT(fixed == 1);
7044
if (!value_cached && !cache_value())
7046
int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val);
7050
double Item_cache_int::val_real()
7052
DBUG_ASSERT(fixed == 1);
7053
if (!value_cached && !cache_value())
7055
return (double) value;
7058
longlong Item_cache_int::val_int()
7060
DBUG_ASSERT(fixed == 1);
7061
if (!value_cached && !cache_value())
7066
bool Item_cache_real::cache_value()
7071
value= example->val_result();
7072
null_value= example->null_value;
7077
double Item_cache_real::val_real()
7079
DBUG_ASSERT(fixed == 1);
7080
if (!value_cached && !cache_value())
7085
longlong Item_cache_real::val_int()
7087
DBUG_ASSERT(fixed == 1);
7088
if (!value_cached && !cache_value())
7090
return (longlong) rint(value);
7094
String* Item_cache_real::val_str(String *str)
7096
DBUG_ASSERT(fixed == 1);
7097
if (!value_cached && !cache_value())
7099
str->set_real(value, decimals, default_charset());
7104
my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val)
7106
DBUG_ASSERT(fixed == 1);
7107
if (!value_cached && !cache_value())
7109
double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
7114
bool Item_cache_decimal::cache_value()
7119
my_decimal *val= example->val_decimal_result(&decimal_value);
7120
if (!(null_value= example->null_value) && val != &decimal_value)
7121
my_decimal2decimal(val, &decimal_value);
7125
double Item_cache_decimal::val_real()
7129
if (!value_cached && !cache_value())
7131
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res);
7135
longlong Item_cache_decimal::val_int()
7139
if (!value_cached && !cache_value())
7141
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res);
7145
String* Item_cache_decimal::val_str(String *str)
7148
if (!value_cached && !cache_value())
7150
my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, FALSE,
7152
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str);
7156
my_decimal *Item_cache_decimal::val_decimal(my_decimal *val)
7159
if (!value_cached && !cache_value())
7161
return &decimal_value;
7165
bool Item_cache_str::cache_value()
7170
value_buff.set(buffer, sizeof(buffer), example->collation.collation);
7171
value= example->str_result(&value_buff);
7172
if ((null_value= example->null_value))
7174
else if (value != &value_buff)
7177
We copy string value to avoid changing value if 'item' is table field
7178
in queries like following (where t1.c is varchar):
7180
(select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'),
7181
(select c from t1 where a=t2.a)
7184
value_buff.copy(*value);
7190
double Item_cache_str::val_real()
7192
DBUG_ASSERT(fixed == 1);
7195
if (!value_cached && !cache_value())
7198
return my_strntod(value->charset(), (char*) value->ptr(),
7199
value->length(), &end_not_used, &err_not_used);
7204
longlong Item_cache_str::val_int()
7206
DBUG_ASSERT(fixed == 1);
7208
if (!value_cached && !cache_value())
7211
return my_strntoll(value->charset(), value->ptr(),
7212
value->length(), 10, (char**) 0, &err);
7218
String* Item_cache_str::val_str(String *str)
7220
DBUG_ASSERT(fixed == 1);
7221
if (!value_cached && !cache_value())
7227
my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val)
7229
DBUG_ASSERT(fixed == 1);
7230
if (!value_cached && !cache_value())
7233
string2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
7240
int Item_cache_str::save_in_field(Field *field, bool no_conversions)
7242
if (!value_cached && !cache_value())
7244
int res= Item_cache::save_in_field(field, no_conversions);
7245
return (is_varbinary && field->type() == MYSQL_TYPE_STRING &&
7246
value->length() < field->field_length) ? 1 : res;
7250
bool Item_cache_row::allocate(uint num)
7253
THD *thd= current_thd;
7255
(Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
7259
bool Item_cache_row::setup(Item * item)
7262
if (!values && allocate(item->cols()))
7264
for (uint i= 0; i < item_count; i++)
7266
Item *el= item->element_index(i);
7268
if (!(tmp= values[i]= Item_cache::get_cache(el)))
7276
void Item_cache_row::store(Item * item)
7284
for (uint i= 0; i < item_count; i++)
7285
values[i]->store(item->element_index(i));
7289
bool Item_cache_row::cache_value()
7295
example->bring_value();
7296
for (uint i= 0; i < item_count; i++)
7298
values[i]->cache_value();
7299
null_value|= values[i]->null_value;
7305
void Item_cache_row::illegal_method_call(const char *method)
7307
DBUG_ENTER("Item_cache_row::illegal_method_call");
7308
DBUG_PRINT("error", ("!!! %s method was called for row item", method));
7310
my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
7315
bool Item_cache_row::check_cols(uint c)
7317
if (c != item_count)
7319
my_error(ER_OPERAND_COLUMNS, MYF(0), c);
7326
bool Item_cache_row::null_inside()
7328
for (uint i= 0; i < item_count; i++)
7330
if (values[i]->cols() > 1)
7332
if (values[i]->null_inside())
7337
values[i]->update_null_value();
7338
if (values[i]->null_value)
7346
void Item_cache_row::bring_value()
7348
for (uint i= 0; i < item_count; i++)
7349
values[i]->bring_value();
7354
Item_type_holder::Item_type_holder(THD *thd, Item *item)
7355
:Item(thd, item), enum_set_typelib(0), fld_type(get_real_type(item))
7357
DBUG_ASSERT(item->fixed);
7358
maybe_null= item->maybe_null;
7359
collation.set(item->collation);
7360
get_full_info(item);
7361
/* fix variable decimals which always is NOT_FIXED_DEC */
7362
if (Field::result_merge_type(fld_type) == INT_RESULT)
7364
prev_decimal_int_part= item->decimal_int_part();
7366
if (item->field_type() == MYSQL_TYPE_GEOMETRY)
7367
geometry_type= item->get_geometry_type();
7368
#endif /* HAVE_SPATIAL */
7373
Return expression type of Item_type_holder.
7376
Item_result (type of internal MySQL expression result)
7379
Item_result Item_type_holder::result_type() const
7381
return Field::result_merge_type(fld_type);
7386
Find real field type of item.
7389
type of field which should be created to store item value
7392
enum_field_types Item_type_holder::get_real_type(Item *item)
7394
switch(item->type())
7399
Item_fields::field_type ask Field_type() but sometimes field return
7400
a different type, like for enum/set, so we need to ask real type.
7402
Field *field= ((Item_field *) item)->field;
7403
enum_field_types type= field->real_type();
7404
if (field->is_created_from_null_item)
7405
return MYSQL_TYPE_NULL;
7406
/* work around about varchar type field detection */
7407
if (type == MYSQL_TYPE_STRING && field->type() == MYSQL_TYPE_VAR_STRING)
7408
return MYSQL_TYPE_VAR_STRING;
7414
Argument of aggregate function sometimes should be asked about field
7417
Item_sum *item_sum= (Item_sum *) item;
7418
if (item_sum->keep_field_type())
7419
return get_real_type(item_sum->get_arg(0));
7423
if (((Item_func *) item)->functype() == Item_func::GUSERVAR_FUNC)
7426
There are work around of problem with changing variable type on the
7427
fly and variable always report "string" as field type to get
7428
acceptable information for client in send_field, so we make field
7429
type from expression type.
7431
switch (item->result_type()) {
7433
return MYSQL_TYPE_VAR_STRING;
7435
return MYSQL_TYPE_LONGLONG;
7437
return MYSQL_TYPE_DOUBLE;
7438
case DECIMAL_RESULT:
7439
return MYSQL_TYPE_NEWDECIMAL;
7443
return MYSQL_TYPE_VAR_STRING;
7450
return item->field_type();
7454
Find field type which can carry current Item_type_holder type and
7457
@param thd thread handler
7458
@param item given item to join its parameters with this item ones
7461
TRUE error - types are incompatible
7466
bool Item_type_holder::join_types(THD *thd, Item *item)
7468
uint max_length_orig= max_length;
7469
uint decimals_orig= decimals;
7470
DBUG_ENTER("Item_type_holder::join_types");
7471
DBUG_PRINT("info:", ("was type %d len %d, dec %d name %s",
7472
fld_type, max_length, decimals,
7473
(name ? name : "<NULL>")));
7474
DBUG_PRINT("info:", ("in type %d len %d, dec %d",
7475
get_real_type(item),
7476
item->max_length, item->decimals));
7477
fld_type= Field::field_type_merge(fld_type, get_real_type(item));
7479
int item_decimals= item->decimals;
7480
/* fix variable decimals which always is NOT_FIXED_DEC */
7481
if (Field::result_merge_type(fld_type) == INT_RESULT)
7483
decimals= max(decimals, item_decimals);
7485
if (Field::result_merge_type(fld_type) == DECIMAL_RESULT)
7487
decimals= min(max(decimals, item->decimals), DECIMAL_MAX_SCALE);
7488
int item_int_part= item->decimal_int_part();
7489
int item_prec = max(prev_decimal_int_part, item_int_part) + decimals;
7490
int precision= min(item_prec, DECIMAL_MAX_PRECISION);
7491
unsigned_flag&= item->unsigned_flag;
7492
max_length= my_decimal_precision_to_length_no_truncation(precision,
7497
switch (Field::result_merge_type(fld_type))
7501
const char *old_cs, *old_derivation;
7502
uint32 old_max_chars= max_length / collation.collation->mbmaxlen;
7503
old_cs= collation.collation->name;
7504
old_derivation= collation.derivation_name();
7505
if (collation.aggregate(item->collation, MY_COLL_ALLOW_CONV))
7507
my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
7508
old_cs, old_derivation,
7509
item->collation.collation->name,
7510
item->collation.derivation_name(),
7515
To figure out max_length, we have to take into account possible
7516
expansion of the size of the values because of character set
7519
if (collation.collation != &my_charset_bin)
7521
max_length= max(old_max_chars * collation.collation->mbmaxlen,
7522
display_length(item) /
7523
item->collation.collation->mbmaxlen *
7524
collation.collation->mbmaxlen);
7527
set_if_bigger(max_length, display_length(item));
7532
if (decimals != NOT_FIXED_DEC)
7535
For FLOAT(M,D)/DOUBLE(M,D) do not change precision
7536
if both fields have the same M and D
7538
if (item->max_length != max_length_orig ||
7539
item->decimals != decimals_orig)
7541
int delta1= max_length_orig - decimals_orig;
7542
int delta2= item->max_length - item->decimals;
7543
max_length= max(delta1, delta2) + decimals;
7544
if (fld_type == MYSQL_TYPE_FLOAT && max_length > FLT_DIG + 2)
7546
max_length= MAX_FLOAT_STR_LENGTH;
7547
decimals= NOT_FIXED_DEC;
7549
else if (fld_type == MYSQL_TYPE_DOUBLE && max_length > DBL_DIG + 2)
7551
max_length= MAX_DOUBLE_STR_LENGTH;
7552
decimals= NOT_FIXED_DEC;
7557
max_length= (fld_type == MYSQL_TYPE_FLOAT) ? FLT_DIG+6 : DBL_DIG+7;
7561
max_length= max(max_length, display_length(item));
7563
maybe_null|= item->maybe_null;
7564
get_full_info(item);
7566
/* Remember decimal integer part to be used in DECIMAL_RESULT handleng */
7567
prev_decimal_int_part= decimal_int_part();
7568
DBUG_PRINT("info", ("become type: %d len: %u dec: %u",
7569
(int) fld_type, max_length, (uint) decimals));
7574
Calculate lenth for merging result for given Item type.
7576
@param item Item for length detection
7582
uint32 Item_type_holder::display_length(Item *item)
7584
if (item->type() == Item::FIELD_ITEM)
7585
return ((Item_field *)item)->max_disp_length();
7587
switch (item->field_type())
7589
case MYSQL_TYPE_DECIMAL:
7590
case MYSQL_TYPE_TIMESTAMP:
7591
case MYSQL_TYPE_DATE:
7592
case MYSQL_TYPE_TIME:
7593
case MYSQL_TYPE_DATETIME:
7594
case MYSQL_TYPE_YEAR:
7595
case MYSQL_TYPE_NEWDATE:
7596
case MYSQL_TYPE_VARCHAR:
7597
case MYSQL_TYPE_BIT:
7598
case MYSQL_TYPE_NEWDECIMAL:
7599
case MYSQL_TYPE_ENUM:
7600
case MYSQL_TYPE_SET:
7601
case MYSQL_TYPE_TINY_BLOB:
7602
case MYSQL_TYPE_MEDIUM_BLOB:
7603
case MYSQL_TYPE_LONG_BLOB:
7604
case MYSQL_TYPE_BLOB:
7605
case MYSQL_TYPE_VAR_STRING:
7606
case MYSQL_TYPE_STRING:
7607
case MYSQL_TYPE_GEOMETRY:
7608
return item->max_length;
7609
case MYSQL_TYPE_TINY:
7611
case MYSQL_TYPE_SHORT:
7613
case MYSQL_TYPE_LONG:
7614
return MY_INT32_NUM_DECIMAL_DIGITS;
7615
case MYSQL_TYPE_FLOAT:
7617
case MYSQL_TYPE_DOUBLE:
7619
case MYSQL_TYPE_NULL:
7621
case MYSQL_TYPE_LONGLONG:
7623
case MYSQL_TYPE_INT24:
7626
DBUG_ASSERT(0); // we should never go there
7633
Make temporary table field according collected information about type
7636
@param table temporary table for which we create fields
7642
Field *Item_type_holder::make_field_by_type(TABLE *table)
7645
The field functions defines a field to be not null if null_ptr is not 0
7647
uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
7651
case MYSQL_TYPE_ENUM:
7652
DBUG_ASSERT(enum_set_typelib);
7653
field= new Field_enum((uchar *) 0, max_length, null_ptr, 0,
7655
get_enum_pack_length(enum_set_typelib->count),
7656
enum_set_typelib, collation.collation);
7660
case MYSQL_TYPE_SET:
7661
DBUG_ASSERT(enum_set_typelib);
7662
field= new Field_set((uchar *) 0, max_length, null_ptr, 0,
7664
get_set_pack_length(enum_set_typelib->count),
7665
enum_set_typelib, collation.collation);
7669
case MYSQL_TYPE_NULL:
7670
return make_string_field(table);
7674
return tmp_table_field_from_field_type(table, 0);
7679
Get full information from Item about enum/set fields to be able to create
7682
@param item Item for information collection
7684
void Item_type_holder::get_full_info(Item *item)
7686
if (fld_type == MYSQL_TYPE_ENUM ||
7687
fld_type == MYSQL_TYPE_SET)
7689
if (item->type() == Item::SUM_FUNC_ITEM &&
7690
(((Item_sum*)item)->sum_func() == Item_sum::MAX_FUNC ||
7691
((Item_sum*)item)->sum_func() == Item_sum::MIN_FUNC))
7692
item = ((Item_sum*)item)->get_arg(0);
7694
We can have enum/set type after merging only if we have one enum|set
7695
field (or MIN|MAX(enum|set field)) and number of NULL fields
7697
DBUG_ASSERT((enum_set_typelib &&
7698
get_real_type(item) == MYSQL_TYPE_NULL) ||
7699
(!enum_set_typelib &&
7700
item->type() == Item::FIELD_ITEM &&
7701
(get_real_type(item) == MYSQL_TYPE_ENUM ||
7702
get_real_type(item) == MYSQL_TYPE_SET) &&
7703
((Field_enum*)((Item_field *) item)->field)->typelib));
7704
if (!enum_set_typelib)
7706
enum_set_typelib= ((Field_enum*)((Item_field *) item)->field)->typelib;
7712
double Item_type_holder::val_real()
7714
DBUG_ASSERT(0); // should never be called
7719
longlong Item_type_holder::val_int()
7721
DBUG_ASSERT(0); // should never be called
7725
my_decimal *Item_type_holder::val_decimal(my_decimal *)
7727
DBUG_ASSERT(0); // should never be called
7731
String *Item_type_holder::val_str(String*)
7733
DBUG_ASSERT(0); // should never be called
7737
void Item_result_field::cleanup()
7739
DBUG_ENTER("Item_result_field::cleanup()");
7746
Dummy error processor used by default by Name_resolution_context.
7752
void dummy_error_processor(THD *thd, void *data)
7756
Wrapper of hide_view_error call for Name_resolution_context error
7760
hide view underlying tables details in error messages
7763
void view_error_processor(THD *thd, void *data)
7765
((TABLE_LIST *)data)->hide_view_error(thd);
7768
/*****************************************************************************
7769
** Instantiate templates
7770
*****************************************************************************/
7772
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
7773
template class List<Item>;
7774
template class List_iterator<Item>;
7775
template class List_iterator_fast<Item>;
7776
template class List_iterator_fast<Item_field>;
7777
template class List<List_item>;