1
/* Copyright (C) 2000-2006 MySQL AB
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 "sql_select.h"
26
const String my_null_string("NULL", 4, default_charset_info);
28
/****************************************************************************/
30
/* Hybrid_type_traits {_real} */
32
void Hybrid_type_traits::fix_length_and_dec(Item *item, Item *arg) const
34
item->decimals= NOT_FIXED_DEC;
35
item->max_length= item->float_length(arg->decimals);
38
static const Hybrid_type_traits real_traits_instance;
40
const Hybrid_type_traits *Hybrid_type_traits::instance()
42
return &real_traits_instance;
47
Hybrid_type_traits::val_decimal(Hybrid_type *val, my_decimal *to) const
49
double2my_decimal(E_DEC_FATAL_ERROR, val->real, val->dec_buf);
55
Hybrid_type_traits::val_str(Hybrid_type *val, String *to, uint8 decimals) const
57
to->set_real(val->real, decimals, &my_charset_bin);
61
/* Hybrid_type_traits_decimal */
62
static const Hybrid_type_traits_decimal decimal_traits_instance;
64
const Hybrid_type_traits_decimal *Hybrid_type_traits_decimal::instance()
66
return &decimal_traits_instance;
71
Hybrid_type_traits_decimal::fix_length_and_dec(Item *item, Item *arg) const
73
item->decimals= arg->decimals;
74
item->max_length= min(arg->max_length + DECIMAL_LONGLONG_DIGITS,
75
DECIMAL_MAX_STR_LENGTH);
79
void Hybrid_type_traits_decimal::set_zero(Hybrid_type *val) const
81
my_decimal_set_zero(&val->dec_buf[0]);
82
val->used_dec_buf_no= 0;
86
void Hybrid_type_traits_decimal::add(Hybrid_type *val, Field *f) const
88
my_decimal_add(E_DEC_FATAL_ERROR,
89
&val->dec_buf[val->used_dec_buf_no ^ 1],
90
&val->dec_buf[val->used_dec_buf_no],
91
f->val_decimal(&val->dec_buf[2]));
92
val->used_dec_buf_no^= 1;
98
what is '4' for scale?
100
void Hybrid_type_traits_decimal::div(Hybrid_type *val, ulonglong u) const
102
int2my_decimal(E_DEC_FATAL_ERROR, u, TRUE, &val->dec_buf[2]);
103
/* XXX: what is '4' for scale? */
104
my_decimal_div(E_DEC_FATAL_ERROR,
105
&val->dec_buf[val->used_dec_buf_no ^ 1],
106
&val->dec_buf[val->used_dec_buf_no],
107
&val->dec_buf[2], 4);
108
val->used_dec_buf_no^= 1;
113
Hybrid_type_traits_decimal::val_int(Hybrid_type *val, bool unsigned_flag) const
116
my_decimal2int(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
117
unsigned_flag, &result);
123
Hybrid_type_traits_decimal::val_real(Hybrid_type *val) const
125
my_decimal2double(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
132
Hybrid_type_traits_decimal::val_str(Hybrid_type *val, String *to,
133
uint8 decimals) const
135
my_decimal_round(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
136
decimals, FALSE, &val->dec_buf[2]);
137
my_decimal2string(E_DEC_FATAL_ERROR, &val->dec_buf[2], 0, 0, 0, to);
141
/* Hybrid_type_traits_integer */
142
static const Hybrid_type_traits_integer integer_traits_instance;
144
const Hybrid_type_traits_integer *Hybrid_type_traits_integer::instance()
146
return &integer_traits_instance;
150
Hybrid_type_traits_integer::fix_length_and_dec(Item *item, Item *arg) const
153
item->max_length= MY_INT64_NUM_DECIMAL_DIGITS;
154
item->unsigned_flag= 0;
157
/*****************************************************************************
159
*****************************************************************************/
162
Init all special items.
173
Make this functions class dependent
176
bool Item::val_bool()
178
switch(result_type()) {
180
return val_int() != 0;
183
my_decimal decimal_value;
184
my_decimal *val= val_decimal(&decimal_value);
186
return !my_decimal_is_zero(val);
191
return val_real() != 0.0;
195
return 0; // Wrong (but safe)
200
String *Item::val_string_from_real(String *str)
202
double nr= val_real();
204
return 0; /* purecov: inspected */
205
str->set_real(nr,decimals, &my_charset_bin);
210
String *Item::val_string_from_int(String *str)
212
longlong nr= val_int();
215
str->set_int(nr, unsigned_flag, &my_charset_bin);
220
String *Item::val_string_from_decimal(String *str)
222
my_decimal dec_buf, *dec= val_decimal(&dec_buf);
225
my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
226
my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
231
my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
233
double nr= val_real();
236
double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
237
return (decimal_value);
241
my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
243
longlong nr= val_int();
246
int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
247
return decimal_value;
251
my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
255
if (!(res= val_str(&str_value)))
256
return 0; // NULL or EOM
258
end_ptr= (char*) res->ptr()+ res->length();
259
if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
260
res->ptr(), res->length(), res->charset(),
261
decimal_value) & E_DEC_BAD_NUM)
263
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
264
ER_TRUNCATED_WRONG_VALUE,
265
ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
268
return decimal_value;
272
my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value)
274
DBUG_ASSERT(fixed == 1);
276
if (get_date(<ime, TIME_FUZZY_DATE))
278
my_decimal_set_zero(decimal_value);
279
null_value= 1; // set NULL, stop processing
282
return date2my_decimal(<ime, decimal_value);
286
my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value)
288
DBUG_ASSERT(fixed == 1);
290
if (get_time(<ime))
292
my_decimal_set_zero(decimal_value);
295
return date2my_decimal(<ime, decimal_value);
299
double Item::val_real_from_decimal()
301
/* Note that fix_fields may not be called for Item_avg_field items */
303
my_decimal value_buff, *dec_val= val_decimal(&value_buff);
306
my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
311
longlong Item::val_int_from_decimal()
313
/* Note that fix_fields may not be called for Item_avg_field items */
315
my_decimal value, *dec_val= val_decimal(&value);
318
my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result);
322
int Item::save_time_in_field(Field *field)
325
if (get_time(<ime))
326
return set_field_to_null(field);
327
field->set_notnull();
328
return field->store_time(<ime, MYSQL_TIMESTAMP_TIME);
332
int Item::save_date_in_field(Field *field)
335
if (get_date(<ime, TIME_FUZZY_DATE))
336
return set_field_to_null(field);
337
field->set_notnull();
338
return field->store_time(<ime, MYSQL_TIMESTAMP_DATETIME);
343
Store the string value in field directly
346
Item::save_str_value_in_field()
347
field a pointer to field where to store
348
result the pointer to the string value to be stored
351
The method is used by Item_*::save_in_field implementations
352
when we don't need to calculate the value to store
353
See Item_string::save_in_field() implementation for example
356
Check if the Item is null and stores the NULL or the
357
result value in the field accordingly.
360
Nonzero value if error
363
int Item::save_str_value_in_field(Field *field, String *result)
366
return set_field_to_null(field);
367
field->set_notnull();
368
return field->store(result->ptr(), result->length(),
369
collation.collation);
374
is_expensive_cache(-1), rsize(0), name(0), orig_name(0), name_length(0),
375
fixed(0), is_autogenerated_name(TRUE),
376
collation(&my_charset_bin, DERIVATION_COERCIBLE)
379
maybe_null=null_value=with_sum_func=unsigned_flag=0;
380
decimals= 0; max_length= 0;
382
cmp_context= (Item_result)-1;
384
/* Put item in free list so that we can free all items at end */
385
THD *thd= current_thd;
386
next= thd->free_list;
387
thd->free_list= this;
389
Item constructor can be called during execution other then SQL_COM
390
command => we should check thd->lex->current_select on zero (thd->lex
391
can be uninitialised)
393
if (thd->lex->current_select)
395
enum_parsing_place place=
396
thd->lex->current_select->parsing_place;
397
if (place == SELECT_LIST ||
399
thd->lex->current_select->select_n_having_items++;
404
Constructor used by Item_field, Item_ref & aggregate (sum)
407
Used for duplicating lists in processing queries with temporary
410
Item::Item(THD *thd, Item *item):
411
is_expensive_cache(-1),
413
str_value(item->str_value),
415
orig_name(item->orig_name),
416
max_length(item->max_length),
417
marker(item->marker),
418
decimals(item->decimals),
419
maybe_null(item->maybe_null),
420
null_value(item->null_value),
421
unsigned_flag(item->unsigned_flag),
422
with_sum_func(item->with_sum_func),
424
collation(item->collation),
425
cmp_context(item->cmp_context)
427
next= thd->free_list; // Put in free list
428
thd->free_list= this;
432
uint Item::decimal_precision() const
434
Item_result restype= result_type();
436
if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
437
return min(my_decimal_length_to_precision(max_length, decimals, unsigned_flag),
438
DECIMAL_MAX_PRECISION);
439
return min(max_length, DECIMAL_MAX_PRECISION);
443
void Item::print_item_w_name(String *str, enum_query_type query_type)
445
print(str, query_type);
449
THD *thd= current_thd;
450
str->append(STRING_WITH_LEN(" AS "));
451
append_identifier(thd, str, name, (uint) strlen(name));
458
DBUG_ENTER("Item::cleanup");
468
cleanup() item if it is 'fixed'.
470
@param arg a dummy parameter, is not used here
473
bool Item::cleanup_processor(uchar *arg)
482
rename item (used for views, cleanup() return original name).
484
@param new_name new name of item;
487
void Item::rename(char *new_name)
490
we can compare pointers to names here, because if name was not changed,
493
if (!orig_name && new_name != name)
500
Traverse item tree possibly transforming it (replacing items).
502
This function is designed to ease transformation of Item trees.
503
Re-execution note: every such transformation is registered for
504
rollback by THD::change_item_tree() and is rolled back at the end
505
of execution by THD::rollback_item_tree_changes().
508
- this function can not be used at prepared statement prepare
509
(in particular, in fix_fields!), as only permanent
510
transformation of Item trees are allowed at prepare.
511
- the transformer function shall allocate new Items in execution
512
memory root (thd->mem_root) and not anywhere else: allocated
513
items will be gone in the end of execution.
515
If you don't need to transform an item tree, but only traverse
516
it, please use Item::walk() instead.
519
@param transformer functor that performs transformation of a subtree
520
@param arg opaque argument passed to the functor
523
Returns pointer to the new subtree root. THD::change_item_tree()
524
should be called for it if transformation took place, i.e. if a
525
pointer to newly allocated item is returned.
528
Item* Item::transform(Item_transformer transformer, uchar *arg)
530
return (this->*transformer)(arg);
534
Item_ident::Item_ident(Name_resolution_context *context_arg,
535
const char *db_name_arg,const char *table_name_arg,
536
const char *field_name_arg)
537
:orig_db_name(db_name_arg), orig_table_name(table_name_arg),
538
orig_field_name(field_name_arg), context(context_arg),
539
db_name(db_name_arg), table_name(table_name_arg),
540
field_name(field_name_arg),
541
alias_name_used(FALSE), cached_field_index(NO_CACHED_FIELD_INDEX),
542
cached_table(0), depended_from(0)
544
name = (char*) field_name_arg;
549
Constructor used by Item_field & Item_*_ref (see Item comment)
552
Item_ident::Item_ident(THD *thd, Item_ident *item)
554
orig_db_name(item->orig_db_name),
555
orig_table_name(item->orig_table_name),
556
orig_field_name(item->orig_field_name),
557
context(item->context),
558
db_name(item->db_name),
559
table_name(item->table_name),
560
field_name(item->field_name),
561
alias_name_used(item->alias_name_used),
562
cached_field_index(item->cached_field_index),
563
cached_table(item->cached_table),
564
depended_from(item->depended_from)
567
void Item_ident::cleanup()
569
DBUG_ENTER("Item_ident::cleanup");
570
#ifdef CANT_BE_USED_AS_MEMORY_IS_FREED
571
db_name ? db_name : "(null)",
572
orig_db_name ? orig_db_name : "(null)",
573
table_name ? table_name : "(null)",
574
orig_table_name ? orig_table_name : "(null)",
575
field_name ? field_name : "(null)",
576
orig_field_name ? orig_field_name : "(null)"));
579
db_name= orig_db_name;
580
table_name= orig_table_name;
581
field_name= orig_field_name;
586
bool Item_ident::remove_dependence_processor(uchar * arg)
588
DBUG_ENTER("Item_ident::remove_dependence_processor");
589
if (depended_from == (st_select_lex *) arg)
596
Store the pointer to this item field into a list if not already there.
598
The method is used by Item::walk to collect all unique Item_field objects
599
from a tree of Items into a set of items represented as a list.
601
Item_cond::walk() and Item_func::walk() stop the evaluation of the
602
processor function for its arguments once the processor returns
603
true.Therefore in order to force this method being called for all item
604
arguments in a condition the method must return false.
606
@param arg pointer to a List<Item_field>
609
FALSE to force the evaluation of collect_item_field_processor
610
for the subsequent items.
613
bool Item_field::collect_item_field_processor(uchar *arg)
615
DBUG_ENTER("Item_field::collect_item_field_processor");
616
DBUG_PRINT("info", ("%s", field->field_name ? field->field_name : "noname"));
617
List<Item_field> *item_list= (List<Item_field>*) arg;
618
List_iterator<Item_field> item_list_it(*item_list);
619
Item_field *curr_item;
620
while ((curr_item= item_list_it++))
622
if (curr_item->eq(this, 1))
623
DBUG_RETURN(FALSE); /* Already in the set. */
625
item_list->push_back(this);
631
Check if an Item_field references some field from a list of fields.
633
Check whether the Item_field represented by 'this' references any
634
of the fields in the keyparts passed via 'arg'. Used with the
635
method Item::walk() to test whether any keypart in a sequence of
636
keyparts is referenced in an expression.
638
@param arg Field being compared, arg must be of type Field
641
TRUE if 'this' references the field 'arg'
646
bool Item_field::find_item_in_field_list_processor(uchar *arg)
648
KEY_PART_INFO *first_non_group_part= *((KEY_PART_INFO **) arg);
649
KEY_PART_INFO *last_part= *(((KEY_PART_INFO **) arg) + 1);
650
KEY_PART_INFO *cur_part;
652
for (cur_part= first_non_group_part; cur_part != last_part; cur_part++)
654
if (field->eq(cur_part->field))
662
Mark field in read_map
665
This is used by filesort to register used fields in a a temporary
666
column read set or to register used fields in a view
669
bool Item_field::register_field_in_read_map(uchar *arg)
671
TABLE *table= (TABLE *) arg;
672
if (field->table == table || !table)
673
bitmap_set_bit(field->table->read_set, field->field_index);
678
bool Item::check_cols(uint c)
682
my_error(ER_OPERAND_COLUMNS, MYF(0), c);
689
void Item::set_name(const char *str, uint length, CHARSET_INFO *cs)
693
/* Empty string, used by AS or internal function like last_insert_id() */
700
uint orig_len= length;
702
This will probably need a better implementation in the future:
703
a function in CHARSET_INFO structure.
705
while (length && !my_isgraph(cs,*str))
706
{ // Fix problem with yacc
710
if (orig_len != length && !is_autogenerated_name)
713
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
714
ER_NAME_BECOMES_EMPTY, ER(ER_NAME_BECOMES_EMPTY),
715
str + length - orig_len);
717
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
718
ER_REMOVED_SPACES, ER(ER_REMOVED_SPACES),
719
str + length - orig_len);
722
if (!my_charset_same(cs, system_charset_info))
725
name= sql_strmake_with_convert(str, name_length= length, cs,
726
MAX_ALIAS_NAME, system_charset_info,
730
name= sql_strmake(str, (name_length= min(length,MAX_ALIAS_NAME)));
736
This function is called when:
737
- Comparing items in the WHERE clause (when doing where optimization)
738
- When trying to find an ORDER BY/GROUP BY item in the SELECT part
741
bool Item::eq(const Item *item, bool binary_cmp) const
744
Note, that this is never TRUE if item is a Item_param:
745
for all basic constants we have special checks, and Item_param's
746
type() can be only among basic constant types.
748
return type() == item->type() && name && item->name &&
749
!my_strcasecmp(system_charset_info,name,item->name);
753
Item *Item::safe_charset_converter(CHARSET_INFO *tocs)
755
Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1);
756
return conv->safe ? conv : NULL;
762
Created mostly for mysql_prepare_table(). Important
763
when a string ENUM/SET column is described with a numeric default value:
765
CREATE TABLE t1(a SET('a') DEFAULT 1);
767
We cannot use generic Item::safe_charset_converter(), because
768
the latter returns a non-fixed Item, so val_str() crashes afterwards.
769
Override Item_num method, to return a fixed item.
771
Item *Item_num::safe_charset_converter(CHARSET_INFO *tocs)
775
String *s, tmp(buf, sizeof(buf), &my_charset_bin);
777
if ((conv= new Item_string(s->ptr(), s->length(), s->charset())))
779
conv->str_value.copy();
780
conv->str_value.mark_as_const();
786
Item *Item_static_float_func::safe_charset_converter(CHARSET_INFO *tocs)
790
String *s, tmp(buf, sizeof(buf), &my_charset_bin);
792
if ((conv= new Item_static_string_func(func_name, s->ptr(), s->length(),
795
conv->str_value.copy();
796
conv->str_value.mark_as_const();
802
Item *Item_string::safe_charset_converter(CHARSET_INFO *tocs)
807
String tmp, cstr, *ostr= val_str(&tmp);
808
cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
809
if (conv_errors || !(conv= new Item_string(cstr.ptr(), cstr.length(),
811
collation.derivation)))
814
Safe conversion is not possible (or EOM).
815
We could not convert a string into the requested character set
816
without data loss. The target charset does not cover all the
817
characters from the string. Operation cannot be done correctly.
821
if (!(ptr= current_thd->strmake(cstr.ptr(), cstr.length())))
823
conv->str_value.set(ptr, cstr.length(), cstr.charset());
824
/* Ensure that no one is going to change the result string */
825
conv->str_value.mark_as_const();
830
Item *Item_param::safe_charset_converter(CHARSET_INFO *tocs)
835
String *ostr= val_str(&cnvstr);
836
cnvitem->str_value.copy(ostr->ptr(), ostr->length(),
837
ostr->charset(), tocs, &cnv_errors);
840
cnvitem->str_value.mark_as_const();
841
cnvitem->max_length= cnvitem->str_value.numchars() * tocs->mbmaxlen;
848
Item *Item_static_string_func::safe_charset_converter(CHARSET_INFO *tocs)
852
String tmp, cstr, *ostr= val_str(&tmp);
853
cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
855
!(conv= new Item_static_string_func(func_name,
856
cstr.ptr(), cstr.length(),
858
collation.derivation)))
861
Safe conversion is not possible (or EOM).
862
We could not convert a string into the requested character set
863
without data loss. The target charset does not cover all the
864
characters from the string. Operation cannot be done correctly.
868
conv->str_value.copy();
869
/* Ensure that no one is going to change the result string */
870
conv->str_value.mark_as_const();
875
bool Item_string::eq(const Item *item, bool binary_cmp) const
877
if (type() == item->type() && item->basic_const_item())
880
return !stringcmp(&str_value, &item->str_value);
881
return (collation.collation == item->collation.collation &&
882
!sortcmp(&str_value, &item->str_value, collation.collation));
889
Get the value of the function as a MYSQL_TIME structure.
890
As a extra convenience the time structure is reset on error!
893
bool Item::get_date(MYSQL_TIME *ltime,uint fuzzydate)
895
if (result_type() == STRING_RESULT)
898
String tmp(buff,sizeof(buff), &my_charset_bin),*res;
899
if (!(res=val_str(&tmp)) ||
900
str_to_datetime_with_warn(res->ptr(), res->length(),
901
ltime, fuzzydate) <= MYSQL_TIMESTAMP_ERROR)
906
longlong value= val_int();
908
if (number_to_datetime(value, ltime, fuzzydate, &was_cut) == LL(-1))
911
end= longlong10_to_str(value, buff, -10);
912
make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
913
buff, (int) (end-buff), MYSQL_TIMESTAMP_NONE,
921
bzero((char*) ltime,sizeof(*ltime));
926
Get time of first argument.\
928
As a extra convenience the time structure is reset on error!
931
bool Item::get_time(MYSQL_TIME *ltime)
934
String tmp(buff,sizeof(buff),&my_charset_bin),*res;
935
if (!(res=val_str(&tmp)) ||
936
str_to_time_with_warn(res->ptr(), res->length(), ltime))
938
bzero((char*) ltime,sizeof(*ltime));
944
CHARSET_INFO *Item::default_charset()
946
return current_thd->variables.collation_connection;
951
Save value in field, but don't give any warnings
954
This is used to temporary store and retrieve a value in a column,
955
for example in opt_range to adjust the key value to fit the column.
958
int Item::save_in_field_no_warnings(Field *field, bool no_conversions)
961
TABLE *table= field->table;
962
THD *thd= table->in_use;
963
enum_check_fields tmp= thd->count_cuted_fields;
964
my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
965
ulong sql_mode= thd->variables.sql_mode;
966
thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
967
thd->count_cuted_fields= CHECK_FIELD_IGNORE;
968
res= save_in_field(field, no_conversions);
969
thd->count_cuted_fields= tmp;
970
dbug_tmp_restore_column_map(table->write_set, old_map);
971
thd->variables.sql_mode= sql_mode;
977
need a special class to adjust printing : references to aggregate functions
978
must not be printed as refs because the aggregate functions that are added to
979
the front of select list are not printed as well.
981
class Item_aggregate_ref : public Item_ref
984
Item_aggregate_ref(Name_resolution_context *context_arg, Item **item,
985
const char *table_name_arg, const char *field_name_arg)
986
:Item_ref(context_arg, item, table_name_arg, field_name_arg) {}
988
virtual inline void print (String *str, enum_query_type query_type)
991
(*ref)->print(str, query_type);
993
Item_ident::print(str, query_type);
999
Move SUM items out from item tree and replace with reference.
1001
@param thd Thread handler
1002
@param ref_pointer_array Pointer to array of reference fields
1003
@param fields All fields in select
1004
@param ref Pointer to item
1005
@param skip_registered <=> function be must skipped for registered
1009
This is from split_sum_func2() for items that should be split
1011
All found SUM items are added FIRST in the fields list and
1012
we replace the item with a reference.
1014
thd->fatal_error() may be called if we are out of memory
1017
void Item::split_sum_func2(THD *thd, Item **ref_pointer_array,
1018
List<Item> &fields, Item **ref,
1019
bool skip_registered)
1021
/* An item of type Item_sum is registered <=> ref_by != 0 */
1022
if (type() == SUM_FUNC_ITEM && skip_registered &&
1023
((Item_sum *) this)->ref_by)
1025
if ((type() != SUM_FUNC_ITEM && with_sum_func) ||
1026
(type() == FUNC_ITEM &&
1027
(((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC ||
1028
((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC)))
1030
/* Will split complicated items and ignore simple ones */
1031
split_sum_func(thd, ref_pointer_array, fields);
1033
else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) &&
1034
type() != SUBSELECT_ITEM &&
1035
(type() != REF_ITEM ||
1036
((Item_ref*)this)->ref_type() == Item_ref::VIEW_REF))
1039
Replace item with a reference so that we can easily calculate
1040
it (in case of sum functions) or copy it (in case of fields)
1042
The test above is to ensure we don't do a reference for things
1043
that are constants (PARAM_TABLE_BIT is in effect a constant)
1044
or already referenced (for example an item in HAVING)
1045
Exception is Item_direct_view_ref which we need to convert to
1046
Item_ref to allow fields from view being stored in tmp table.
1048
Item_aggregate_ref *item_ref;
1049
uint el= fields.elements;
1050
Item *real_itm= real_item();
1052
ref_pointer_array[el]= real_itm;
1053
if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context,
1054
ref_pointer_array + el, 0, name)))
1055
return; // fatal_error is set
1056
if (type() == SUM_FUNC_ITEM)
1057
item_ref->depended_from= ((Item_sum *) this)->depended_from();
1058
fields.push_front(real_itm);
1059
thd->change_item_tree(ref, item_ref);
1065
left_is_superset(DTCollation *left, DTCollation *right)
1067
/* Allow convert to Unicode */
1068
if (left->collation->state & MY_CS_UNICODE &&
1069
(left->derivation < right->derivation ||
1070
(left->derivation == right->derivation &&
1071
!(right->collation->state & MY_CS_UNICODE))))
1073
/* Allow convert from ASCII */
1074
if (right->repertoire == MY_REPERTOIRE_ASCII &&
1075
(left->derivation < right->derivation ||
1076
(left->derivation == right->derivation &&
1077
!(left->repertoire == MY_REPERTOIRE_ASCII))))
1079
/* Disallow conversion otherwise */
1084
Aggregate two collations together taking
1085
into account their coercibility (aka derivation):.
1087
0 == DERIVATION_EXPLICIT - an explicitly written COLLATE clause @n
1088
1 == DERIVATION_NONE - a mix of two different collations @n
1089
2 == DERIVATION_IMPLICIT - a column @n
1090
3 == DERIVATION_COERCIBLE - a string constant.
1092
The most important rules are:
1093
-# If collations are the same:
1094
chose this collation, and the strongest derivation.
1095
-# If collations are different:
1096
- Character sets may differ, but only if conversion without
1097
data loss is possible. The caller provides flags whether
1098
character set conversion attempts should be done. If no
1099
flags are substituted, then the character sets must be the same.
1100
Currently processed flags are:
1101
MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset
1102
MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
1103
- two EXPLICIT collations produce an error, e.g. this is wrong:
1104
CONCAT(expr1 collate latin1_swedish_ci, expr2 collate latin1_german_ci)
1105
- the side with smaller derivation value wins,
1106
i.e. a column is stronger than a string constant,
1107
an explicit COLLATE clause is stronger than a column.
1108
- if derivations are the same, we have DERIVATION_NONE,
1109
we'll wait for an explicit COLLATE clause which possibly can
1110
come from another argument later: for example, this is valid,
1111
but we don't know yet when collecting the first two arguments:
1113
CONCAT(latin1_swedish_ci_column,
1114
latin1_german1_ci_column,
1115
expr COLLATE latin1_german2_ci)
1119
bool DTCollation::aggregate(DTCollation &dt, uint flags)
1121
if (!my_charset_same(collation, dt.collation))
1124
We do allow to use binary strings (like BLOBS)
1125
together with character strings.
1126
Binaries have more precedence than a character
1127
string of the same derivation.
1129
if (collation == &my_charset_bin)
1131
if (derivation <= dt.derivation)
1138
else if (dt.collation == &my_charset_bin)
1140
if (dt.derivation <= derivation)
1149
else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
1150
left_is_superset(this, &dt))
1154
else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
1155
left_is_superset(&dt, this))
1159
else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
1160
derivation < dt.derivation &&
1161
dt.derivation >= DERIVATION_SYSCONST)
1165
else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
1166
dt.derivation < derivation &&
1167
derivation >= DERIVATION_SYSCONST)
1173
// Cannot apply conversion
1174
set(0, DERIVATION_NONE, 0);
1178
else if (derivation < dt.derivation)
1182
else if (dt.derivation < derivation)
1188
if (collation == dt.collation)
1194
if (derivation == DERIVATION_EXPLICIT)
1196
set(0, DERIVATION_NONE, 0);
1199
if (collation->state & MY_CS_BINSORT)
1201
if (dt.collation->state & MY_CS_BINSORT)
1206
CHARSET_INFO *bin= get_charset_by_csname(collation->csname,
1207
MY_CS_BINSORT,MYF(0));
1208
set(bin, DERIVATION_NONE);
1211
repertoire|= dt.repertoire;
1215
/******************************/
1217
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname)
1219
my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
1220
c1.collation->name,c1.derivation_name(),
1221
c2.collation->name,c2.derivation_name(),
1227
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, DTCollation &c3,
1230
my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0),
1231
c1.collation->name,c1.derivation_name(),
1232
c2.collation->name,c2.derivation_name(),
1233
c3.collation->name,c3.derivation_name(),
1239
void my_coll_agg_error(Item** args, uint count, const char *fname,
1243
my_coll_agg_error(args[0]->collation, args[item_sep]->collation, fname);
1244
else if (count == 3)
1245
my_coll_agg_error(args[0]->collation, args[item_sep]->collation,
1246
args[2*item_sep]->collation, fname);
1248
my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname);
1252
bool agg_item_collations(DTCollation &c, const char *fname,
1253
Item **av, uint count, uint flags, int item_sep)
1257
c.set(av[0]->collation);
1258
for (i= 1, arg= &av[item_sep]; i < count; i++, arg++)
1260
if (c.aggregate((*arg)->collation, flags))
1262
my_coll_agg_error(av, count, fname, item_sep);
1266
if ((flags & MY_COLL_DISALLOW_NONE) &&
1267
c.derivation == DERIVATION_NONE)
1269
my_coll_agg_error(av, count, fname, item_sep);
1276
bool agg_item_collations_for_comparison(DTCollation &c, const char *fname,
1277
Item **av, uint count, uint flags)
1279
return (agg_item_collations(c, fname, av, count,
1280
flags | MY_COLL_DISALLOW_NONE, 1));
1285
Collect arguments' character sets together.
1287
We allow to apply automatic character set conversion in some cases.
1288
The conditions when conversion is possible are:
1289
- arguments A and B have different charsets
1290
- A wins according to coercibility rules
1291
(i.e. a column is stronger than a string constant,
1292
an explicit COLLATE clause is stronger than a column)
1293
- character set of A is either superset for character set of B,
1294
or B is a string constant which can be converted into the
1295
character set of A without data loss.
1297
If all of the above is true, then it's possible to convert
1298
B into the character set of A, and then compare according
1299
to the collation of A.
1301
For functions with more than two arguments:
1303
collect(A,B,C) ::= collect(collect(A,B),C)
1305
Since this function calls THD::change_item_tree() on the passed Item **
1306
pointers, it is necessary to pass the original Item **'s, not copies.
1307
Otherwise their values will not be properly restored (see BUG#20769).
1308
If the items are not consecutive (eg. args[2] and args[5]), use the
1309
item_sep argument, ie.
1311
agg_item_charsets(coll, fname, &args[2], 2, flags, 3)
1315
bool agg_item_charsets(DTCollation &coll, const char *fname,
1316
Item **args, uint nargs, uint flags, int item_sep)
1318
Item **arg, *safe_args[2];
1320
memset(safe_args, 0, sizeof(safe_args));
1322
if (agg_item_collations(coll, fname, args, nargs, flags, item_sep))
1326
For better error reporting: save the first and the second argument.
1327
We need this only if the the number of args is 3 or 2:
1328
- for a longer argument list, "Illegal mix of collations"
1329
doesn't display each argument's characteristics.
1330
- if nargs is 1, then this error cannot happen.
1332
if (nargs >=2 && nargs <= 3)
1334
safe_args[0]= args[0];
1335
safe_args[1]= args[item_sep];
1338
THD *thd= current_thd;
1339
Query_arena *arena, backup;
1343
In case we're in statement prepare, create conversion item
1344
in its memory: it will be reused on each execute.
1348
for (i= 0, arg= args; i < nargs; i++, arg+= item_sep)
1351
uint32 dummy_offset;
1352
if (!String::needs_conversion(0, (*arg)->collation.collation,
1357
if (!(conv= (*arg)->safe_charset_converter(coll.collation)) &&
1358
((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII))
1359
conv= new Item_func_conv_charset(*arg, coll.collation, 1);
1363
if (nargs >=2 && nargs <= 3)
1365
/* restore the original arguments for better error message */
1366
args[0]= safe_args[0];
1367
args[item_sep]= safe_args[1];
1369
my_coll_agg_error(args, nargs, fname, item_sep);
1371
break; // we cannot return here, we need to restore "arena".
1373
if ((*arg)->type() == Item::FIELD_ITEM)
1374
((Item_field *)(*arg))->no_const_subst= 1;
1376
If in statement prepare, then we create a converter for two
1377
constant items, do it once and then reuse it.
1378
If we're in execution of a prepared statement, arena is NULL,
1379
and the conv was created in runtime memory. This can be
1380
the case only if the argument is a parameter marker ('?'),
1381
because for all true constants the charset converter has already
1382
been created in prepare. In this case register the change for
1385
thd->change_item_tree(arg, conv);
1387
We do not check conv->fixed, because Item_func_conv_charset which can
1388
be return by safe_charset_converter can't be fixed at creation
1390
conv->fix_fields(thd, arg);
1393
thd->restore_active_arena(arena, &backup);
1398
void Item_ident_for_show::make_field(Send_field *tmp_field)
1400
tmp_field->table_name= tmp_field->org_table_name= table_name;
1401
tmp_field->db_name= db_name;
1402
tmp_field->col_name= tmp_field->org_col_name= field->field_name;
1403
tmp_field->charsetnr= field->charset()->number;
1404
tmp_field->length=field->field_length;
1405
tmp_field->type=field->type();
1406
tmp_field->flags= field->table->maybe_null ?
1407
(field->flags & ~NOT_NULL_FLAG) : field->flags;
1408
tmp_field->decimals= field->decimals();
1411
/**********************************************/
1413
Item_field::Item_field(Field *f)
1414
:Item_ident(0, NullS, *f->table_name, f->field_name),
1415
item_equal(0), no_const_subst(0),
1416
have_privileges(0), any_privileges(0)
1420
field_name and table_name should not point to garbage
1421
if this item is to be reused
1423
orig_table_name= orig_field_name= "";
1428
Constructor used inside setup_wild().
1430
Ensures that field, table, and database names will live as long as
1431
Item_field (this is important in prepared statements).
1434
Item_field::Item_field(THD *thd, Name_resolution_context *context_arg,
1436
:Item_ident(context_arg, f->table->s->db.str, *f->table_name, f->field_name),
1437
item_equal(0), no_const_subst(0),
1438
have_privileges(0), any_privileges(0)
1444
Item_field::Item_field(Name_resolution_context *context_arg,
1445
const char *db_arg,const char *table_name_arg,
1446
const char *field_name_arg)
1447
:Item_ident(context_arg, db_arg,table_name_arg,field_name_arg),
1448
field(0), result_field(0), item_equal(0), no_const_subst(0),
1449
have_privileges(0), any_privileges(0)
1451
SELECT_LEX *select= current_thd->lex->current_select;
1452
collation.set(DERIVATION_IMPLICIT);
1453
if (select && select->parsing_place != IN_HAVING)
1454
select->select_n_where_fields++;
1458
Constructor need to process subselect with temporary tables (see Item)
1461
Item_field::Item_field(THD *thd, Item_field *item)
1462
:Item_ident(thd, item),
1464
result_field(item->result_field),
1465
item_equal(item->item_equal),
1466
no_const_subst(item->no_const_subst),
1467
have_privileges(item->have_privileges),
1468
any_privileges(item->any_privileges)
1470
collation.set(DERIVATION_IMPLICIT);
1473
void Item_field::set_field(Field *field_par)
1475
field=result_field=field_par; // for easy coding with fields
1476
maybe_null=field->maybe_null();
1477
decimals= field->decimals();
1478
max_length= field_par->max_display_length();
1479
table_name= *field_par->table_name;
1480
field_name= field_par->field_name;
1481
db_name= field_par->table->s->db.str;
1482
alias_name_used= field_par->table->alias_name_used;
1483
unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
1484
collation.set(field_par->charset(), field_par->derivation());
1486
if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
1492
Reset this item to point to a field from the new temporary table.
1493
This is used when we create a new temporary table for each execution
1494
of prepared statement.
1497
void Item_field::reset_field(Field *f)
1500
/* 'name' is pointing at field->field_name of old field */
1501
name= (char*) f->field_name;
1504
const char *Item_ident::full_name() const
1507
if (!table_name || !field_name)
1508
return field_name ? field_name : name ? name : "tmp_field";
1509
if (db_name && db_name[0])
1511
tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
1512
(uint) strlen(field_name)+3);
1513
strxmov(tmp,db_name,".",table_name,".",field_name,NullS);
1519
tmp= (char*) sql_alloc((uint) strlen(table_name) +
1520
(uint) strlen(field_name) + 2);
1521
strxmov(tmp, table_name, ".", field_name, NullS);
1524
tmp= (char*) field_name;
1529
void Item_ident::print(String *str, enum_query_type query_type)
1531
THD *thd= current_thd;
1532
char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
1533
const char *d_name= db_name, *t_name= table_name;
1534
if (lower_case_table_names== 1 ||
1535
(lower_case_table_names == 2 && !alias_name_used))
1537
if (table_name && table_name[0])
1539
strmov(t_name_buff, table_name);
1540
my_casedn_str(files_charset_info, t_name_buff);
1541
t_name= t_name_buff;
1543
if (db_name && db_name[0])
1545
strmov(d_name_buff, db_name);
1546
my_casedn_str(files_charset_info, d_name_buff);
1547
d_name= d_name_buff;
1551
if (!table_name || !field_name || !field_name[0])
1553
const char *nm= (field_name && field_name[0]) ?
1554
field_name : name ? name : "tmp_field";
1555
append_identifier(thd, str, nm, (uint) strlen(nm));
1558
if (db_name && db_name[0] && !alias_name_used)
1561
append_identifier(thd, str, d_name, (uint)strlen(d_name));
1564
append_identifier(thd, str, t_name, (uint)strlen(t_name));
1566
append_identifier(thd, str, field_name, (uint)strlen(field_name));
1572
append_identifier(thd, str, t_name, (uint) strlen(t_name));
1574
append_identifier(thd, str, field_name, (uint) strlen(field_name));
1577
append_identifier(thd, str, field_name, (uint) strlen(field_name));
1582
String *Item_field::val_str(String *str)
1584
DBUG_ASSERT(fixed == 1);
1585
if ((null_value=field->is_null()))
1587
str->set_charset(str_value.charset());
1588
return field->val_str(str,&str_value);
1592
double Item_field::val_real()
1594
DBUG_ASSERT(fixed == 1);
1595
if ((null_value=field->is_null()))
1597
return field->val_real();
1601
longlong Item_field::val_int()
1603
DBUG_ASSERT(fixed == 1);
1604
if ((null_value=field->is_null()))
1606
return field->val_int();
1610
my_decimal *Item_field::val_decimal(my_decimal *decimal_value)
1612
if ((null_value= field->is_null()))
1614
return field->val_decimal(decimal_value);
1618
String *Item_field::str_result(String *str)
1620
if ((null_value=result_field->is_null()))
1622
str->set_charset(str_value.charset());
1623
return result_field->val_str(str,&str_value);
1626
bool Item_field::get_date(MYSQL_TIME *ltime,uint fuzzydate)
1628
if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
1630
bzero((char*) ltime,sizeof(*ltime));
1636
bool Item_field::get_date_result(MYSQL_TIME *ltime,uint fuzzydate)
1638
if ((null_value=result_field->is_null()) ||
1639
result_field->get_date(ltime,fuzzydate))
1641
bzero((char*) ltime,sizeof(*ltime));
1647
bool Item_field::get_time(MYSQL_TIME *ltime)
1649
if ((null_value=field->is_null()) || field->get_time(ltime))
1651
bzero((char*) ltime,sizeof(*ltime));
1657
double Item_field::val_result()
1659
if ((null_value=result_field->is_null()))
1661
return result_field->val_real();
1664
longlong Item_field::val_int_result()
1666
if ((null_value=result_field->is_null()))
1668
return result_field->val_int();
1672
my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value)
1674
if ((null_value= result_field->is_null()))
1676
return result_field->val_decimal(decimal_value);
1680
bool Item_field::val_bool_result()
1682
if ((null_value= result_field->is_null()))
1684
switch (result_field->result_type()) {
1686
return result_field->val_int() != 0;
1687
case DECIMAL_RESULT:
1689
my_decimal decimal_value;
1690
my_decimal *val= result_field->val_decimal(&decimal_value);
1692
return !my_decimal_is_zero(val);
1697
return result_field->val_real() != 0.0;
1701
return 0; // Shut up compiler
1706
bool Item_field::eq(const Item *item, bool binary_cmp) const
1708
Item *real_item= ((Item *) item)->real_item();
1709
if (real_item->type() != FIELD_ITEM)
1712
Item_field *item_field= (Item_field*) real_item;
1713
if (item_field->field && field)
1714
return item_field->field == field;
1716
We may come here when we are trying to find a function in a GROUP BY
1717
clause from the select list.
1718
In this case the '100 % correct' way to do this would be to first
1719
run fix_fields() on the GROUP BY item and then retry this function, but
1720
I think it's better to relax the checking a bit as we will in
1721
most cases do the correct thing by just checking the field name.
1722
(In cases where we would choose wrong we would have to generate a
1725
return (!my_strcasecmp(system_charset_info, item_field->name,
1727
(!item_field->table_name || !table_name ||
1728
(!my_strcasecmp(table_alias_charset, item_field->table_name,
1730
(!item_field->db_name || !db_name ||
1731
(item_field->db_name && !strcmp(item_field->db_name,
1736
table_map Item_field::used_tables() const
1738
if (field->table->const_table)
1739
return 0; // const item
1740
return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
1744
void Item_field::fix_after_pullout(st_select_lex *new_parent, Item **ref)
1746
if (new_parent == depended_from)
1747
depended_from= NULL;
1748
Name_resolution_context *ctx= new Name_resolution_context();
1749
ctx->outer_context= NULL; // We don't build a complete name resolver
1750
ctx->select_lex= new_parent;
1751
ctx->first_name_resolution_table= context->first_name_resolution_table;
1752
ctx->last_name_resolution_table= context->last_name_resolution_table;
1757
Item *Item_field::get_tmp_table_item(THD *thd)
1759
Item_field *new_item= new Item_field(thd, this);
1761
new_item->field= new_item->result_field;
1765
longlong Item_field::val_int_endpoint(bool left_endp, bool *incl_endp)
1767
longlong res= val_int();
1768
return null_value? LONGLONG_MIN : res;
1772
Create an item from a string we KNOW points to a valid longlong
1773
end \\0 terminated number string.
1774
This is always 'signed'. Unsigned values are created with Item_uint()
1777
Item_int::Item_int(const char *str_arg, uint length)
1779
char *end_ptr= (char*) str_arg + length;
1781
value= my_strtoll10(str_arg, &end_ptr, &error);
1782
max_length= (uint) (end_ptr - str_arg);
1783
name= (char*) str_arg;
1788
my_decimal *Item_int::val_decimal(my_decimal *decimal_value)
1790
int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_value);
1791
return decimal_value;
1794
String *Item_int::val_str(String *str)
1796
// following assert is redundant, because fixed=1 assigned in constructor
1797
DBUG_ASSERT(fixed == 1);
1798
str->set(value, &my_charset_bin);
1802
void Item_int::print(String *str, enum_query_type query_type)
1804
// my_charset_bin is good enough for numbers
1805
str_value.set(value, &my_charset_bin);
1806
str->append(str_value);
1810
Item_uint::Item_uint(const char *str_arg, uint length):
1811
Item_int(str_arg, length)
1817
Item_uint::Item_uint(const char *str_arg, longlong i, uint length):
1818
Item_int(str_arg, i, length)
1824
String *Item_uint::val_str(String *str)
1826
// following assert is redundant, because fixed=1 assigned in constructor
1827
DBUG_ASSERT(fixed == 1);
1828
str->set((ulonglong) value, &my_charset_bin);
1833
void Item_uint::print(String *str, enum_query_type query_type)
1835
// latin1 is good enough for numbers
1836
str_value.set((ulonglong) value, default_charset());
1837
str->append(str_value);
1841
Item_decimal::Item_decimal(const char *str_arg, uint length,
1842
CHARSET_INFO *charset)
1844
str2my_decimal(E_DEC_FATAL_ERROR, str_arg, length, charset, &decimal_value);
1845
name= (char*) str_arg;
1846
decimals= (uint8) decimal_value.frac;
1848
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1849
decimals, unsigned_flag);
1852
Item_decimal::Item_decimal(longlong val, bool unsig)
1854
int2my_decimal(E_DEC_FATAL_ERROR, val, unsig, &decimal_value);
1855
decimals= (uint8) decimal_value.frac;
1857
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1858
decimals, unsigned_flag);
1862
Item_decimal::Item_decimal(double val, int precision, int scale)
1864
double2my_decimal(E_DEC_FATAL_ERROR, val, &decimal_value);
1865
decimals= (uint8) decimal_value.frac;
1867
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1868
decimals, unsigned_flag);
1872
Item_decimal::Item_decimal(const char *str, const my_decimal *val_arg,
1873
uint decimal_par, uint length)
1875
my_decimal2decimal(val_arg, &decimal_value);
1877
decimals= (uint8) decimal_par;
1883
Item_decimal::Item_decimal(my_decimal *value_par)
1885
my_decimal2decimal(value_par, &decimal_value);
1886
decimals= (uint8) decimal_value.frac;
1888
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1889
decimals, unsigned_flag);
1893
Item_decimal::Item_decimal(const uchar *bin, int precision, int scale)
1895
binary2my_decimal(E_DEC_FATAL_ERROR, bin,
1896
&decimal_value, precision, scale);
1897
decimals= (uint8) decimal_value.frac;
1899
max_length= my_decimal_precision_to_length(precision, decimals,
1904
longlong Item_decimal::val_int()
1907
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &result);
1911
double Item_decimal::val_real()
1914
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
1918
String *Item_decimal::val_str(String *result)
1920
result->set_charset(&my_charset_bin);
1921
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, result);
1925
void Item_decimal::print(String *str, enum_query_type query_type)
1927
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, &str_value);
1928
str->append(str_value);
1932
bool Item_decimal::eq(const Item *item, bool binary_cmp) const
1934
if (type() == item->type() && item->basic_const_item())
1937
We need to cast off const to call val_decimal(). This should
1938
be OK for a basic constant. Additionally, we can pass 0 as
1939
a true decimal constant will return its internal decimal
1940
storage and ignore the argument.
1942
Item *arg= (Item*) item;
1943
my_decimal *value= arg->val_decimal(0);
1944
return !my_decimal_cmp(&decimal_value, value);
1950
void Item_decimal::set_decimal_value(my_decimal *value_par)
1952
my_decimal2decimal(value_par, &decimal_value);
1953
decimals= (uint8) decimal_value.frac;
1954
unsigned_flag= !decimal_value.sign();
1955
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1956
decimals, unsigned_flag);
1960
String *Item_float::val_str(String *str)
1962
// following assert is redundant, because fixed=1 assigned in constructor
1963
DBUG_ASSERT(fixed == 1);
1964
str->set_real(value,decimals,&my_charset_bin);
1969
my_decimal *Item_float::val_decimal(my_decimal *decimal_value)
1971
// following assert is redundant, because fixed=1 assigned in constructor
1972
DBUG_ASSERT(fixed == 1);
1973
double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_value);
1974
return (decimal_value);
1978
void Item_string::print(String *str, enum_query_type query_type)
1980
if (query_type == QT_ORDINARY && is_cs_specified())
1983
str->append(collation.collation->csname);
1988
if (query_type == QT_ORDINARY ||
1989
my_charset_same(str_value.charset(), system_charset_info))
1991
str_value.print(str);
1995
THD *thd= current_thd;
1996
LEX_STRING utf8_lex_str;
1998
thd->convert_string(&utf8_lex_str,
1999
system_charset_info,
2000
str_value.c_ptr_safe(),
2002
str_value.charset());
2004
String utf8_str(utf8_lex_str.str,
2005
utf8_lex_str.length,
2006
system_charset_info);
2008
utf8_str.print(str);
2015
double Item_string::val_real()
2017
DBUG_ASSERT(fixed == 1);
2019
char *end, *org_end;
2021
CHARSET_INFO *cs= str_value.charset();
2023
org_end= (char*) str_value.ptr() + str_value.length();
2024
tmp= my_strntod(cs, (char*) str_value.ptr(), str_value.length(), &end,
2026
if (error || (end != org_end && !check_if_only_end_space(cs, end, org_end)))
2029
We can use str_value.ptr() here as Item_string is gurantee to put an
2032
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2033
ER_TRUNCATED_WRONG_VALUE,
2034
ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
2043
Give error if we wanted a signed integer and we got an unsigned one
2045
longlong Item_string::val_int()
2047
DBUG_ASSERT(fixed == 1);
2050
char *end= (char*) str_value.ptr()+ str_value.length();
2052
CHARSET_INFO *cs= str_value.charset();
2054
tmp= (*(cs->cset->strtoll10))(cs, str_value.ptr(), &end, &err);
2056
TODO: Give error if we wanted a signed integer and we got an unsigned
2060
(end != org_end && !check_if_only_end_space(cs, end, org_end)))
2062
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2063
ER_TRUNCATED_WRONG_VALUE,
2064
ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
2071
my_decimal *Item_string::val_decimal(my_decimal *decimal_value)
2073
return val_decimal_from_string(decimal_value);
2077
bool Item_null::eq(const Item *item, bool binary_cmp) const
2078
{ return item->type() == type(); }
2081
double Item_null::val_real()
2083
// following assert is redundant, because fixed=1 assigned in constructor
2084
DBUG_ASSERT(fixed == 1);
2088
longlong Item_null::val_int()
2090
// following assert is redundant, because fixed=1 assigned in constructor
2091
DBUG_ASSERT(fixed == 1);
2096
String *Item_null::val_str(String *str)
2098
// following assert is redundant, because fixed=1 assigned in constructor
2099
DBUG_ASSERT(fixed == 1);
2104
my_decimal *Item_null::val_decimal(my_decimal *decimal_value)
2110
Item *Item_null::safe_charset_converter(CHARSET_INFO *tocs)
2112
collation.set(tocs);
2116
/*********************** Item_param related ******************************/
2119
Default function of Item_param::set_param_func, so in case
2120
of malformed packet the server won't SIGSEGV.
2124
default_set_param_func(Item_param *param,
2125
uchar **pos __attribute__((unused)),
2126
ulong len __attribute__((unused)))
2132
Item_param::Item_param(uint pos_in_query_arg) :
2134
item_result_type(STRING_RESULT),
2135
/* Don't pretend to be a literal unless value for this item is set. */
2136
item_type(PARAM_ITEM),
2137
param_type(MYSQL_TYPE_VARCHAR),
2138
pos_in_query(pos_in_query_arg),
2139
set_param_func(default_set_param_func),
2140
limit_clause_param(FALSE)
2144
Since we can't say whenever this item can be NULL or cannot be NULL
2145
before mysql_stmt_execute(), so we assuming that it can be NULL until
2149
cnvitem= new Item_string("", 0, &my_charset_bin, DERIVATION_COERCIBLE);
2150
cnvstr.set(cnvbuf, sizeof(cnvbuf), &my_charset_bin);
2154
void Item_param::set_null()
2156
DBUG_ENTER("Item_param::set_null");
2157
/* These are cleared after each execution by reset() method */
2160
Because of NULL and string values we need to set max_length for each new
2161
placeholder value: user can submit NULL for any placeholder type, and
2162
string length can be different in each execution.
2167
item_type= Item::NULL_ITEM;
2171
void Item_param::set_int(longlong i, uint32 max_length_arg)
2173
DBUG_ENTER("Item_param::set_int");
2174
value.integer= (longlong) i;
2176
max_length= max_length_arg;
2182
void Item_param::set_double(double d)
2184
DBUG_ENTER("Item_param::set_double");
2187
max_length= DBL_DIG + 8;
2188
decimals= NOT_FIXED_DEC;
2195
Set decimal parameter value from string.
2197
@param str character string
2198
@param length string length
2201
As we use character strings to send decimal values in
2202
binary protocol, we use str2my_decimal to convert it to
2203
internal decimal value.
2206
void Item_param::set_decimal(const char *str, ulong length)
2209
DBUG_ENTER("Item_param::set_decimal");
2211
end= (char*) str+length;
2212
str2my_decimal(E_DEC_FATAL_ERROR, str, &decimal_value, &end);
2213
state= DECIMAL_VALUE;
2214
decimals= decimal_value.frac;
2215
max_length= my_decimal_precision_to_length(decimal_value.precision(),
2216
decimals, unsigned_flag);
2223
Set parameter value from MYSQL_TIME value.
2225
@param tm datetime value to set (time_type is ignored)
2226
@param type type of datetime value
2227
@param max_length_arg max length of datetime value as string
2230
If we value to be stored is not normalized, zero value will be stored
2231
instead and proper warning will be produced. This function relies on
2232
the fact that even wrong value sent over binary protocol fits into
2233
MAX_DATE_STRING_REP_LENGTH buffer.
2235
void Item_param::set_time(MYSQL_TIME *tm, timestamp_type time_type,
2236
uint32 max_length_arg)
2238
DBUG_ENTER("Item_param::set_time");
2241
value.time.time_type= time_type;
2243
if (value.time.year > 9999 || value.time.month > 12 ||
2244
value.time.day > 31 ||
2245
((time_type != MYSQL_TIMESTAMP_TIME) && value.time.hour > 23) ||
2246
value.time.minute > 59 || value.time.second > 59)
2248
char buff[MAX_DATE_STRING_REP_LENGTH];
2249
uint length= my_TIME_to_str(&value.time, buff);
2250
make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2251
buff, length, time_type, 0);
2252
set_zero_time(&value.time, MYSQL_TIMESTAMP_ERROR);
2257
max_length= max_length_arg;
2263
bool Item_param::set_str(const char *str, ulong length)
2265
DBUG_ENTER("Item_param::set_str");
2267
Assign string with no conversion: data is converted only after it's
2268
been written to the binary log.
2271
if (str_value.copy(str, length, &my_charset_bin, &my_charset_bin,
2274
state= STRING_VALUE;
2277
/* max_length and decimals are set after charset conversion */
2278
/* sic: str may be not null-terminated, don't add DBUG_PRINT here */
2283
bool Item_param::set_longdata(const char *str, ulong length)
2285
DBUG_ENTER("Item_param::set_longdata");
2288
If client character set is multibyte, end of long data packet
2289
may hit at the middle of a multibyte character. Additionally,
2290
if binary log is open we must write long data value to the
2291
binary log in character set of client. This is why we can't
2292
convert long data to connection character set as it comes
2293
(here), and first have to concatenate all pieces together,
2294
write query to the binary log and only then perform conversion.
2296
if (str_value.append(str, length, &my_charset_bin))
2298
state= LONG_DATA_VALUE;
2306
Set parameter value from user variable value.
2308
@param thd Current thread
2309
@param entry User variable structure (NULL means use NULL value)
2317
bool Item_param::set_from_user_var(THD *thd, const user_var_entry *entry)
2319
DBUG_ENTER("Item_param::set_from_user_var");
2320
if (entry && entry->value)
2322
item_result_type= entry->type;
2323
unsigned_flag= entry->unsigned_flag;
2324
if (limit_clause_param)
2327
set_int(entry->val_int(&unused), MY_INT64_NUM_DECIMAL_DIGITS);
2328
item_type= Item::INT_ITEM;
2329
DBUG_RETURN(!unsigned_flag && value.integer < 0 ? 1 : 0);
2331
switch (item_result_type) {
2333
set_double(*(double*)entry->value);
2334
item_type= Item::REAL_ITEM;
2337
set_int(*(longlong*)entry->value, MY_INT64_NUM_DECIMAL_DIGITS);
2338
item_type= Item::INT_ITEM;
2342
CHARSET_INFO *fromcs= entry->collation.collation;
2343
CHARSET_INFO *tocs= thd->variables.collation_connection;
2344
uint32 dummy_offset;
2346
value.cs_info.character_set_of_placeholder=
2347
value.cs_info.character_set_client= fromcs;
2349
Setup source and destination character sets so that they
2350
are different only if conversion is necessary: this will
2351
make later checks easier.
2353
value.cs_info.final_character_set_of_str_value=
2354
String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
2357
Exact value of max_length is not known unless data is converted to
2358
charset of connection, so we have to set it later.
2360
item_type= Item::STRING_ITEM;
2362
if (set_str((const char *)entry->value, entry->length))
2366
case DECIMAL_RESULT:
2368
const my_decimal *ent_value= (const my_decimal *)entry->value;
2369
my_decimal2decimal(ent_value, &decimal_value);
2370
state= DECIMAL_VALUE;
2371
decimals= ent_value->frac;
2372
max_length= my_decimal_precision_to_length(ent_value->precision(),
2373
decimals, unsigned_flag);
2374
item_type= Item::DECIMAL_ITEM;
2389
Resets parameter after execution.
2392
We clear null_value here instead of setting it in set_* methods,
2393
because we want more easily handle case for long data.
2396
void Item_param::reset()
2398
DBUG_ENTER("Item_param::reset");
2399
/* Shrink string buffer if it's bigger than max possible CHAR column */
2400
if (str_value.alloced_length() > MAX_CHAR_WIDTH)
2403
str_value.length(0);
2404
str_value_ptr.length(0);
2406
We must prevent all charset conversions until data has been written
2409
str_value.set_charset(&my_charset_bin);
2410
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
2415
Don't reset item_type to PARAM_ITEM: it's only needed to guard
2416
us from item optimizations at prepare stage, when item doesn't yet
2417
contain a literal of some kind.
2418
In all other cases when this object is accessed its value is
2419
set (this assumption is guarded by 'state' and
2420
DBUG_ASSERTS(state != NO_VALUE) in all Item_param::get_*
2427
int Item_param::save_in_field(Field *field, bool no_conversions)
2429
field->set_notnull();
2433
return field->store(value.integer, unsigned_flag);
2435
return field->store(value.real);
2437
return field->store_decimal(&decimal_value);
2439
field->store_time(&value.time, value.time.time_type);
2442
case LONG_DATA_VALUE:
2443
return field->store(str_value.ptr(), str_value.length(),
2444
str_value.charset());
2446
return set_field_to_null_with_conversions(field, no_conversions);
2455
bool Item_param::get_time(MYSQL_TIME *res)
2457
if (state == TIME_VALUE)
2463
If parameter value isn't supplied assertion will fire in val_str()
2464
which is called from Item::get_time().
2466
return Item::get_time(res);
2470
bool Item_param::get_date(MYSQL_TIME *res, uint fuzzydate)
2472
if (state == TIME_VALUE)
2477
return Item::get_date(res, fuzzydate);
2481
double Item_param::val_real()
2487
return (double) value.integer;
2491
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
2495
case LONG_DATA_VALUE:
2499
return my_strntod(str_value.charset(), (char*) str_value.ptr(),
2500
str_value.length(), &end_not_used, &dummy_err);
2504
This works for example when user says SELECT ?+0.0 and supplies
2505
time value for the placeholder.
2507
return ulonglong2double(TIME_to_ulonglong(&value.time));
2517
longlong Item_param::val_int()
2521
return (longlong) rint(value.real);
2523
return value.integer;
2527
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &i);
2531
case LONG_DATA_VALUE:
2534
return my_strntoll(str_value.charset(), str_value.ptr(),
2535
str_value.length(), 10, (char**) 0, &dummy_err);
2538
return (longlong) TIME_to_ulonglong(&value.time);
2548
my_decimal *Item_param::val_decimal(my_decimal *dec)
2552
return &decimal_value;
2554
double2my_decimal(E_DEC_FATAL_ERROR, value.real, dec);
2557
int2my_decimal(E_DEC_FATAL_ERROR, value.integer, unsigned_flag, dec);
2560
case LONG_DATA_VALUE:
2561
string2my_decimal(E_DEC_FATAL_ERROR, &str_value, dec);
2565
longlong i= (longlong) TIME_to_ulonglong(&value.time);
2566
int2my_decimal(E_DEC_FATAL_ERROR, i, 0, dec);
2578
String *Item_param::val_str(String* str)
2582
case LONG_DATA_VALUE:
2583
return &str_value_ptr;
2585
str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
2588
str->set(value.integer, &my_charset_bin);
2591
if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
2597
if (str->reserve(MAX_DATE_STRING_REP_LENGTH))
2599
str->length((uint) my_TIME_to_str(&value.time, (char*) str->ptr()));
2600
str->set_charset(&my_charset_bin);
2612
Return Param item values in string format, for generating the dynamic
2613
query used in update/binary logs.
2616
- Change interface and implementation to fill log data in place
2617
and avoid one more memcpy/alloc between str and log string.
2618
- In case of error we need to notify replication
2619
that binary log contains wrong statement
2622
const String *Item_param::query_val_str(String* str) const
2626
str->set_int(value.integer, unsigned_flag, &my_charset_bin);
2629
str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
2632
if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
2634
return &my_null_string;
2641
TODO: in case of error we need to notify replication
2642
that binary log contains wrong statement
2644
if (str->reserve(MAX_DATE_STRING_REP_LENGTH+3))
2647
/* Create date string inplace */
2648
buf= str->c_ptr_quick();
2651
ptr+= (uint) my_TIME_to_str(&value.time, ptr);
2653
str->length((uint32) (ptr - buf));
2657
case LONG_DATA_VALUE:
2660
append_query_string(value.cs_info.character_set_client, &str_value, str);
2664
return &my_null_string;
2673
Convert string from client character set to the character set of
2677
bool Item_param::convert_str_value(THD *thd)
2680
if (state == STRING_VALUE || state == LONG_DATA_VALUE)
2683
Check is so simple because all charsets were set up properly
2684
in setup_one_conversion_function, where typecode of
2685
placeholder was also taken into account: the variables are different
2686
here only if conversion is really necessary.
2688
if (value.cs_info.final_character_set_of_str_value !=
2689
value.cs_info.character_set_of_placeholder)
2691
rc= thd->convert_string(&str_value,
2692
value.cs_info.character_set_of_placeholder,
2693
value.cs_info.final_character_set_of_str_value);
2696
str_value.set_charset(value.cs_info.final_character_set_of_str_value);
2697
/* Here str_value is guaranteed to be in final_character_set_of_str_value */
2699
max_length= str_value.length();
2702
str_value_ptr is returned from val_str(). It must be not alloced
2703
to prevent it's modification by val_str() invoker.
2705
str_value_ptr.set(str_value.ptr(), str_value.length(),
2706
str_value.charset());
2707
/* Synchronize item charset with value charset */
2708
collation.set(str_value.charset(), DERIVATION_COERCIBLE);
2714
bool Item_param::basic_const_item() const
2716
if (state == NO_VALUE || state == TIME_VALUE)
2723
Item_param::clone_item()
2725
/* see comments in the header file */
2728
return new Item_null(name);
2730
return (unsigned_flag ?
2731
new Item_uint(name, value.integer, max_length) :
2732
new Item_int(name, value.integer, max_length));
2734
return new Item_float(name, value.real, decimals, max_length);
2736
case LONG_DATA_VALUE:
2737
return new Item_string(name, str_value.c_ptr_quick(), str_value.length(),
2738
str_value.charset());
2750
Item_param::eq(const Item *arg, bool binary_cmp) const
2753
if (!basic_const_item() || !arg->basic_const_item() || arg->type() != type())
2756
We need to cast off const to call val_int(). This should be OK for
2765
return value.integer == item->val_int() &&
2766
unsigned_flag == item->unsigned_flag;
2768
return value.real == item->val_real();
2770
case LONG_DATA_VALUE:
2772
return !stringcmp(&str_value, &item->str_value);
2773
return !sortcmp(&str_value, &item->str_value, collation.collation);
2780
/* End of Item_param related */
2782
void Item_param::print(String *str, enum_query_type query_type)
2784
if (state == NO_VALUE)
2790
char buffer[STRING_BUFFER_USUAL_SIZE];
2791
String tmp(buffer, sizeof(buffer), &my_charset_bin);
2793
res= query_val_str(&tmp);
2799
/****************************************************************************
2801
****************************************************************************/
2803
void Item_copy_string::copy()
2805
String *res=item->val_str(&str_value);
2806
if (res && res != &str_value)
2807
str_value.copy(*res);
2808
null_value=item->null_value;
2812
String *Item_copy_string::val_str(String *str)
2814
// Item_copy_string is used without fix_fields call
2821
my_decimal *Item_copy_string::val_decimal(my_decimal *decimal_value)
2823
// Item_copy_string is used without fix_fields call
2826
string2my_decimal(E_DEC_FATAL_ERROR, &str_value, decimal_value);
2827
return (decimal_value);
2832
Functions to convert item to field (for send_fields)
2836
bool Item::fix_fields(THD *thd, Item **ref)
2839
// We do not check fields which are fixed during construction
2840
DBUG_ASSERT(fixed == 0 || basic_const_item());
2845
double Item_ref_null_helper::val_real()
2847
DBUG_ASSERT(fixed == 1);
2848
double tmp= (*ref)->val_result();
2849
owner->was_null|= null_value= (*ref)->null_value;
2854
longlong Item_ref_null_helper::val_int()
2856
DBUG_ASSERT(fixed == 1);
2857
longlong tmp= (*ref)->val_int_result();
2858
owner->was_null|= null_value= (*ref)->null_value;
2863
my_decimal *Item_ref_null_helper::val_decimal(my_decimal *decimal_value)
2865
DBUG_ASSERT(fixed == 1);
2866
my_decimal *val= (*ref)->val_decimal_result(decimal_value);
2867
owner->was_null|= null_value= (*ref)->null_value;
2872
bool Item_ref_null_helper::val_bool()
2874
DBUG_ASSERT(fixed == 1);
2875
bool val= (*ref)->val_bool_result();
2876
owner->was_null|= null_value= (*ref)->null_value;
2881
String* Item_ref_null_helper::val_str(String* s)
2883
DBUG_ASSERT(fixed == 1);
2884
String* tmp= (*ref)->str_result(s);
2885
owner->was_null|= null_value= (*ref)->null_value;
2890
bool Item_ref_null_helper::get_date(MYSQL_TIME *ltime, uint fuzzydate)
2892
return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate));
2897
Mark item and SELECT_LEXs as dependent if item was resolved in
2900
@param thd thread handler
2901
@param last select from which current item depend
2902
@param current current select
2903
@param resolved_item item which was resolved in outer SELECT(for warning)
2904
@param mark_item item which should be marked (can be differ in case of
2908
static void mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current,
2909
Item_ident *resolved_item,
2910
Item_ident *mark_item)
2912
const char *db_name= (resolved_item->db_name ?
2913
resolved_item->db_name : "");
2914
const char *table_name= (resolved_item->table_name ?
2915
resolved_item->table_name : "");
2916
/* store pointer on SELECT_LEX from which item is dependent */
2918
mark_item->depended_from= last;
2919
current->mark_as_dependent(last);
2920
if (thd->lex->describe & DESCRIBE_EXTENDED)
2922
char warn_buff[MYSQL_ERRMSG_SIZE];
2923
sprintf(warn_buff, ER(ER_WARN_FIELD_RESOLVED),
2924
db_name, (db_name[0] ? "." : ""),
2925
table_name, (table_name [0] ? "." : ""),
2926
resolved_item->field_name,
2927
current->select_number, last->select_number);
2928
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
2929
ER_WARN_FIELD_RESOLVED, warn_buff);
2935
Mark range of selects and resolved identifier (field/reference)
2938
@param thd thread handler
2939
@param last_select select where resolved_item was resolved
2940
@param current_sel current select (select where resolved_item was placed)
2941
@param found_field field which was found during resolving
2942
@param found_item Item which was found during resolving (if resolved
2943
identifier belongs to VIEW)
2944
@param resolved_item Identifier which was resolved
2947
We have to mark all items between current_sel (including) and
2948
last_select (excluding) as dependend (select before last_select should
2949
be marked with actual table mask used by resolved item, all other with
2950
OUTER_REF_TABLE_BIT) and also write dependence information to Item of
2951
resolved identifier.
2954
void mark_select_range_as_dependent(THD *thd,
2955
SELECT_LEX *last_select,
2956
SELECT_LEX *current_sel,
2957
Field *found_field, Item *found_item,
2958
Item_ident *resolved_item)
2961
Go from current SELECT to SELECT where field was resolved (it
2962
have to be reachable from current SELECT, because it was already
2963
done once when we resolved this field and cached result of
2966
SELECT_LEX *previous_select= current_sel;
2967
for (; previous_select->outer_select() != last_select;
2968
previous_select= previous_select->outer_select())
2970
Item_subselect *prev_subselect_item=
2971
previous_select->master_unit()->item;
2972
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
2973
prev_subselect_item->const_item_cache= 0;
2976
Item_subselect *prev_subselect_item=
2977
previous_select->master_unit()->item;
2978
Item_ident *dependent= resolved_item;
2979
if (found_field == view_ref_found)
2981
Item::Type type= found_item->type();
2982
prev_subselect_item->used_tables_cache|=
2983
found_item->used_tables();
2984
dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
2985
(Item_ident*) found_item :
2989
prev_subselect_item->used_tables_cache|=
2990
found_field->table->map;
2991
prev_subselect_item->const_item_cache= 0;
2992
mark_as_dependent(thd, last_select, current_sel, resolved_item,
2999
Search a GROUP BY clause for a field with a certain name.
3001
Search the GROUP BY list for a column named as find_item. When searching
3002
preference is given to columns that are qualified with the same table (and
3003
database) name as the one being searched for.
3005
@param find_item the item being searched for
3006
@param group_list GROUP BY clause
3009
- the found item on success
3010
- NULL if find_item is not in group_list
3013
static Item** find_field_in_group_list(Item *find_item, ORDER *group_list)
3015
const char *db_name;
3016
const char *table_name;
3017
const char *field_name;
3018
ORDER *found_group= NULL;
3019
int found_match_degree= 0;
3020
Item_ident *cur_field;
3021
int cur_match_degree= 0;
3022
char name_buff[NAME_LEN+1];
3024
if (find_item->type() == Item::FIELD_ITEM ||
3025
find_item->type() == Item::REF_ITEM)
3027
db_name= ((Item_ident*) find_item)->db_name;
3028
table_name= ((Item_ident*) find_item)->table_name;
3029
field_name= ((Item_ident*) find_item)->field_name;
3034
if (db_name && lower_case_table_names)
3036
/* Convert database to lower case for comparison */
3037
strmake(name_buff, db_name, sizeof(name_buff)-1);
3038
my_casedn_str(files_charset_info, name_buff);
3042
DBUG_ASSERT(field_name != 0);
3044
for (ORDER *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
3046
if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM)
3048
cur_field= (Item_ident*) *cur_group->item;
3049
cur_match_degree= 0;
3051
DBUG_ASSERT(cur_field->field_name != 0);
3053
if (!my_strcasecmp(system_charset_info,
3054
cur_field->field_name, field_name))
3059
if (cur_field->table_name && table_name)
3061
/* If field_name is qualified by a table name. */
3062
if (my_strcasecmp(table_alias_charset, cur_field->table_name, table_name))
3063
/* Same field names, different tables. */
3067
if (cur_field->db_name && db_name)
3069
/* If field_name is also qualified by a database name. */
3070
if (strcmp(cur_field->db_name, db_name))
3071
/* Same field names, different databases. */
3077
if (cur_match_degree > found_match_degree)
3079
found_match_degree= cur_match_degree;
3080
found_group= cur_group;
3082
else if (found_group && (cur_match_degree == found_match_degree) &&
3083
! (*(found_group->item))->eq(cur_field, 0))
3086
If the current resolve candidate matches equally well as the current
3087
best match, they must reference the same column, otherwise the field
3090
my_error(ER_NON_UNIQ_ERROR, MYF(0),
3091
find_item->full_name(), current_thd->where);
3098
return found_group->item;
3105
Resolve a column reference in a sub-select.
3107
Resolve a column reference (usually inside a HAVING clause) against the
3108
SELECT and GROUP BY clauses of the query described by 'select'. The name
3109
resolution algorithm searches both the SELECT and GROUP BY clauses, and in
3110
case of a name conflict prefers GROUP BY column names over SELECT names. If
3111
both clauses contain different fields with the same names, a warning is
3112
issued that name of 'ref' is ambiguous. We extend ANSI SQL in that when no
3113
GROUP BY column is found, then a HAVING name is resolved as a possibly
3114
derived SELECT column. This extension is allowed only if the
3115
MODE_ONLY_FULL_GROUP_BY sql mode isn't enabled.
3117
@param thd current thread
3118
@param ref column reference being resolved
3119
@param select the select that ref is resolved against
3122
The resolution procedure is:
3123
- Search for a column or derived column named col_ref_i [in table T_j]
3124
in the SELECT clause of Q.
3125
- Search for a column named col_ref_i [in table T_j]
3126
in the GROUP BY clause of Q.
3127
- If found different columns with the same name in GROUP BY and SELECT
3128
- issue a warning and return the GROUP BY column,
3130
- if the MODE_ONLY_FULL_GROUP_BY mode is enabled return error
3131
- else return the found SELECT column.
3135
- NULL - there was an error, and the error was already reported
3136
- not_found_item - the item was not resolved, no error was reported
3137
- resolved item - if the item was resolved
3141
resolve_ref_in_select_and_group(THD *thd, Item_ident *ref, SELECT_LEX *select)
3143
Item **group_by_ref= NULL;
3144
Item **select_ref= NULL;
3145
ORDER *group_list= (ORDER*) select->group_list.first;
3146
bool ambiguous_fields= FALSE;
3148
enum_resolution_type resolution;
3151
Search for a column or derived column named as 'ref' in the SELECT
3152
clause of the current select.
3154
if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()),
3155
&counter, REPORT_EXCEPT_NOT_FOUND,
3157
return NULL; /* Some error occurred. */
3158
if (resolution == RESOLVED_AGAINST_ALIAS)
3159
ref->alias_name_used= TRUE;
3161
/* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
3162
if (select->having_fix_field && !ref->with_sum_func && group_list)
3164
group_by_ref= find_field_in_group_list(ref, group_list);
3166
/* Check if the fields found in SELECT and GROUP BY are the same field. */
3167
if (group_by_ref && (select_ref != not_found_item) &&
3168
!((*group_by_ref)->eq(*select_ref, 0)))
3170
ambiguous_fields= TRUE;
3171
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
3172
ER(ER_NON_UNIQ_ERROR), ref->full_name(),
3173
current_thd->where);
3178
if (select_ref != not_found_item || group_by_ref)
3180
if (select_ref != not_found_item && !ambiguous_fields)
3182
DBUG_ASSERT(*select_ref != 0);
3183
if (!select->ref_pointer_array[counter])
3185
my_error(ER_ILLEGAL_REFERENCE, MYF(0),
3186
ref->name, "forward reference in item list");
3189
DBUG_ASSERT((*select_ref)->fixed);
3190
return (select->ref_pointer_array + counter);
3193
return group_by_ref;
3195
return NULL; /* So there is no compiler warning. */
3198
return (Item**) not_found_item;
3203
Resolve the name of an outer select column reference.
3205
The method resolves the column reference represented by 'this' as a column
3206
present in outer selects that contain current select.
3208
In prepared statements, because of cache, find_field_in_tables()
3209
can resolve fields even if they don't belong to current context.
3210
In this case this method only finds appropriate context and marks
3211
current select as dependent. The found reference of field should be
3212
provided in 'from_field'.
3214
@param[in] thd current thread
3215
@param[in,out] from_field found field reference or (Field*)not_found_field
3216
@param[in,out] reference view column if this item was resolved to a
3220
This is the inner loop of Item_field::fix_fields:
3222
for each outer query Q_k beginning from the inner-most one
3224
search for a column or derived column named col_ref_i
3225
[in table T_j] in the FROM clause of Q_k;
3227
if such a column is not found
3228
Search for a column or derived column named col_ref_i
3229
[in table T_j] in the SELECT and GROUP clauses of Q_k.
3234
1 column succefully resolved and fix_fields() should continue.
3236
0 column fully fixed and fix_fields() should return FALSE
3242
Item_field::fix_outer_field(THD *thd, Field **from_field, Item **reference)
3244
enum_parsing_place place= NO_MATTER;
3245
bool field_found= (*from_field != not_found_field);
3246
bool upward_lookup= FALSE;
3249
If there are outer contexts (outer selects, but current select is
3250
not derived table or view) try to resolve this reference in the
3253
We treat each subselect as a separate namespace, so that different
3254
subselects may contain columns with the same names. The subselects
3255
are searched starting from the innermost.
3257
Name_resolution_context *last_checked_context= context;
3258
Item **ref= (Item **) not_found_item;
3259
SELECT_LEX *current_sel= (SELECT_LEX *) thd->lex->current_select;
3260
Name_resolution_context *outer_context= 0;
3261
SELECT_LEX *select= 0;
3262
/* Currently derived tables cannot be correlated */
3263
if (current_sel->master_unit()->first_select()->linkage !=
3265
outer_context= context->outer_context;
3268
outer_context= outer_context->outer_context)
3270
select= outer_context->select_lex;
3271
Item_subselect *prev_subselect_item=
3272
last_checked_context->select_lex->master_unit()->item;
3273
last_checked_context= outer_context;
3274
upward_lookup= TRUE;
3276
place= prev_subselect_item->parsing_place;
3278
If outer_field is set, field was already found by first call
3279
to find_field_in_tables(). Only need to find appropriate context.
3281
if (field_found && outer_context->select_lex !=
3282
cached_table->select_lex)
3285
In case of a view, find_field_in_tables() writes the pointer to
3286
the found view field into '*reference', in other words, it
3287
substitutes this Item_field with the found expression.
3289
if (field_found || (*from_field= find_field_in_tables(thd, this,
3291
first_name_resolution_table,
3293
last_name_resolution_table,
3295
IGNORE_EXCEPT_NON_UNIQUE,
3301
if (*from_field != view_ref_found)
3303
prev_subselect_item->used_tables_cache|= (*from_field)->table->map;
3304
prev_subselect_item->const_item_cache= 0;
3305
set_field(*from_field);
3306
if (!last_checked_context->select_lex->having_fix_field &&
3307
select->group_list.elements &&
3308
(place == SELECT_LIST || place == IN_HAVING))
3312
If an outer field is resolved in a grouping select then it
3313
is replaced for an Item_outer_ref object. Otherwise an
3314
Item_field object is used.
3315
The new Item_outer_ref object is saved in the inner_refs_list of
3316
the outer select. Here it is only created. It can be fixed only
3317
after the original field has been fixed and this is done in the
3318
fix_inner_refs() function.
3321
if (!(rf= new Item_outer_ref(context, this)))
3323
thd->change_item_tree(reference, rf);
3324
select->inner_refs_list.push_back(rf);
3325
rf->in_sum_func= thd->lex->in_sum_func;
3328
A reference is resolved to a nest level that's outer or the same as
3329
the nest level of the enclosing set function : adjust the value of
3330
max_arg_level for the function if it's needed.
3332
if (thd->lex->in_sum_func &&
3333
thd->lex->in_sum_func->nest_level >= select->nest_level)
3335
Item::Type ref_type= (*reference)->type();
3336
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
3337
select->nest_level);
3338
set_field(*from_field);
3340
mark_as_dependent(thd, last_checked_context->select_lex,
3341
context->select_lex, this,
3342
((ref_type == REF_ITEM ||
3343
ref_type == FIELD_ITEM) ?
3344
(Item_ident*) (*reference) : 0));
3350
Item::Type ref_type= (*reference)->type();
3351
prev_subselect_item->used_tables_cache|=
3352
(*reference)->used_tables();
3353
prev_subselect_item->const_item_cache&=
3354
(*reference)->const_item();
3355
mark_as_dependent(thd, last_checked_context->select_lex,
3356
context->select_lex, this,
3357
((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ?
3358
(Item_ident*) (*reference) :
3361
A reference to a view field had been found and we
3362
substituted it instead of this Item (find_field_in_tables
3363
does it by assigning the new value to *reference), so now
3364
we can return from this function.
3372
/* Search in SELECT and GROUP lists of the outer select. */
3373
if (place != IN_WHERE && place != IN_ON)
3375
if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
3376
return -1; /* Some error occurred (e.g. ambiguous names). */
3377
if (ref != not_found_item)
3379
DBUG_ASSERT(*ref && (*ref)->fixed);
3380
prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
3381
prev_subselect_item->const_item_cache&= (*ref)->const_item();
3387
Reference is not found in this select => this subquery depend on
3388
outer select (or we just trying to find wrong identifier, in this
3389
case it does not matter which used tables bits we set)
3391
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
3392
prev_subselect_item->const_item_cache= 0;
3395
DBUG_ASSERT(ref != 0);
3398
if (ref == not_found_item && *from_field == not_found_field)
3402
// We can't say exactly what absent table or field
3403
my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where);
3407
/* Call find_field_in_tables only to report the error */
3408
find_field_in_tables(thd, this,
3409
context->first_name_resolution_table,
3410
context->last_name_resolution_table,
3411
reference, REPORT_ALL_ERRORS,
3417
else if (ref != not_found_item)
3422
/* Should have been checked in resolve_ref_in_select_and_group(). */
3423
DBUG_ASSERT(*ref && (*ref)->fixed);
3425
Here, a subset of actions performed by Item_ref::set_properties
3426
is not enough. So we pass ptr to NULL into Item_[direct]_ref
3427
constructor, so no initialization is performed, and call
3431
*ref= NULL; // Don't call set_properties()
3432
rf= (place == IN_HAVING ?
3433
new Item_ref(context, ref, (char*) table_name,
3434
(char*) field_name, alias_name_used) :
3435
(!select->group_list.elements ?
3436
new Item_direct_ref(context, ref, (char*) table_name,
3437
(char*) field_name, alias_name_used) :
3438
new Item_outer_ref(context, ref, (char*) table_name,
3439
(char*) field_name, alias_name_used)));
3444
if (place != IN_HAVING && select->group_list.elements)
3446
outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf);
3447
((Item_outer_ref*)rf)->in_sum_func= thd->lex->in_sum_func;
3449
thd->change_item_tree(reference, rf);
3451
rf is Item_ref => never substitute other items (in this case)
3452
during fix_fields() => we can use rf after fix_fields()
3454
DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
3455
if (rf->fix_fields(thd, reference) || rf->check_cols(1))
3458
mark_as_dependent(thd, last_checked_context->select_lex,
3459
context->select_lex, this,
3465
mark_as_dependent(thd, last_checked_context->select_lex,
3466
context->select_lex,
3467
this, (Item_ident*)*reference);
3468
if (last_checked_context->select_lex->having_fix_field)
3471
rf= new Item_ref(context,
3472
(cached_table->db[0] ? cached_table->db : 0),
3473
(char*) cached_table->alias, (char*) field_name);
3476
thd->change_item_tree(reference, rf);
3478
rf is Item_ref => never substitute other items (in this case)
3479
during fix_fields() => we can use rf after fix_fields()
3481
DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
3482
if (rf->fix_fields(thd, reference) || rf->check_cols(1))
3492
Resolve the name of a column reference.
3494
The method resolves the column reference represented by 'this' as a column
3495
present in one of: FROM clause, SELECT clause, GROUP BY clause of a query
3496
Q, or in outer queries that contain Q.
3498
The name resolution algorithm used is (where [T_j] is an optional table
3499
name that qualifies the column name):
3502
resolve_column_reference([T_j].col_ref_i)
3504
search for a column or derived column named col_ref_i
3505
[in table T_j] in the FROM clause of Q;
3507
if such a column is NOT found AND // Lookup in outer queries.
3508
there are outer queries
3510
for each outer query Q_k beginning from the inner-most one
3512
search for a column or derived column named col_ref_i
3513
[in table T_j] in the FROM clause of Q_k;
3515
if such a column is not found
3516
Search for a column or derived column named col_ref_i
3517
[in table T_j] in the SELECT and GROUP clauses of Q_k.
3523
Notice that compared to Item_ref::fix_fields, here we first search the FROM
3524
clause, and then we search the SELECT and GROUP BY clauses.
3526
@param[in] thd current thread
3527
@param[in,out] reference view column if this item was resolved to a
3536
bool Item_field::fix_fields(THD *thd, Item **reference)
3538
DBUG_ASSERT(fixed == 0);
3539
Field *from_field= (Field *)not_found_field;
3540
bool outer_fixed= false;
3542
if (!field) // If field is not checked
3545
In case of view, find_field_in_tables() write pointer to view field
3546
expression to 'reference', i.e. it substitute that expression instead
3549
if ((from_field= find_field_in_tables(thd, this,
3550
context->first_name_resolution_table,
3551
context->last_name_resolution_table,
3553
thd->lex->use_only_table_context ?
3555
IGNORE_EXCEPT_NON_UNIQUE,
3561
/* Look up in current select's item_list to find aliased fields */
3562
if (thd->lex->current_select->is_item_list_lookup)
3565
enum_resolution_type resolution;
3566
Item** res= find_item_in_list(this, thd->lex->current_select->item_list,
3567
&counter, REPORT_EXCEPT_NOT_FOUND,
3571
if (resolution == RESOLVED_AGAINST_ALIAS)
3572
alias_name_used= TRUE;
3573
if (res != (Item **)not_found_item)
3575
if ((*res)->type() == Item::FIELD_ITEM)
3578
It's an Item_field referencing another Item_field in the select
3580
Use the field from the Item_field in the select list and leave
3581
the Item_field instance in place.
3584
Field *new_field= (*((Item_field**)res))->field;
3586
if (new_field == NULL)
3588
/* The column to which we link isn't valid. */
3589
my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->name,
3590
current_thd->where);
3594
set_field(new_field);
3600
It's not an Item_field in the select list so we must make a new
3601
Item_ref to point to the Item in the select list and replace the
3602
Item_field created by the parser with the new Item_ref.
3604
Item_ref *rf= new Item_ref(context, db_name,table_name,field_name);
3607
thd->change_item_tree(reference, rf);
3609
Because Item_ref never substitutes itself with other items
3610
in Item_ref::fix_fields(), we can safely use the original
3611
pointer to it even after fix_fields()
3613
return rf->fix_fields(thd, reference) || rf->check_cols(1);
3617
if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
3621
goto mark_non_agg_field;
3623
else if (!from_field)
3626
if (!outer_fixed && cached_table && cached_table->select_lex &&
3627
context->select_lex &&
3628
cached_table->select_lex != context->select_lex)
3631
if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
3635
goto mark_non_agg_field;
3639
if it is not expression from merged VIEW we will set this field.
3641
We can leave expression substituted from view for next PS/SP rexecution
3642
(i.e. do not register this substitution for reverting on cleanup()
3643
(register_item_tree_changing())), because this subtree will be
3644
fix_field'ed during setup_tables()->setup_underlying() (i.e. before
3645
all other expressions of query, and references on tables which do
3646
not present in query will not make problems.
3648
Also we suppose that view can't be changed during PS/SP life.
3650
if (from_field == view_ref_found)
3653
set_field(from_field);
3654
if (thd->lex->in_sum_func &&
3655
thd->lex->in_sum_func->nest_level ==
3656
thd->lex->current_select->nest_level)
3657
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
3658
thd->lex->current_select->nest_level);
3660
else if (thd->mark_used_columns != MARK_COLUMNS_NONE)
3662
TABLE *table= field->table;
3663
MY_BITMAP *current_bitmap, *other_bitmap;
3664
if (thd->mark_used_columns == MARK_COLUMNS_READ)
3666
current_bitmap= table->read_set;
3667
other_bitmap= table->write_set;
3671
current_bitmap= table->write_set;
3672
other_bitmap= table->read_set;
3674
if (!bitmap_fast_test_and_set(current_bitmap, field->field_index))
3676
if (!bitmap_is_set(other_bitmap, field->field_index))
3678
/* First usage of column */
3679
table->used_fields++; // Used to optimize loops
3680
/* purecov: begin inspected */
3681
table->covering_keys.intersect(field->part_of_key);
3691
context->process_error(thd);
3695
Item *Item_field::safe_charset_converter(CHARSET_INFO *tocs)
3698
return Item::safe_charset_converter(tocs);
3702
void Item_field::cleanup()
3704
DBUG_ENTER("Item_field::cleanup");
3705
Item_ident::cleanup();
3707
Even if this object was created by direct link to field in setup_wild()
3708
it will be linked correctly next time by name of field and table alias.
3709
I.e. we can drop 'field'.
3711
field= result_field= 0;
3717
Find a field among specified multiple equalities.
3719
The function first searches the field among multiple equalities
3720
of the current level (in the cond_equal->current_level list).
3721
If it fails, it continues searching in upper levels accessed
3722
through a pointer cond_equal->upper_levels.
3723
The search terminates as soon as a multiple equality containing
3726
@param cond_equal reference to list of multiple equalities where
3727
the field (this object) is to be looked for
3730
- First Item_equal containing the field, if success
3734
Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal)
3736
Item_equal *item= 0;
3739
List_iterator_fast<Item_equal> li(cond_equal->current_level);
3740
while ((item= li++))
3742
if (item->contains(field))
3746
The field is not found in any of the multiple equalities
3747
of the current level. Look for it in upper levels
3749
cond_equal= cond_equal->upper_levels;
3756
Check whether a field can be substituted by an equal item.
3758
The function checks whether a substitution of the field
3759
occurrence for an equal item is valid.
3761
@param arg *arg != NULL <-> the field is in the context where
3762
substitution for an equal item is valid
3765
The following statement is not always true:
3769
This means substitution of an item for an equal item not always
3770
yields an equavalent condition. Here's an example:
3773
(LENGTH('a')=1) != (LENGTH('a ')=2)
3775
Such a substitution is surely valid if either the substituted
3776
field is not of a STRING type or if it is an argument of
3777
a comparison predicate.
3780
TRUE substitution is valid
3785
bool Item_field::subst_argument_checker(uchar **arg)
3787
return (result_type() != STRING_RESULT) || (*arg);
3792
Convert a numeric value to a zero-filled string
3794
@param[in,out] item the item to operate on
3795
@param field The field that this value is equated to
3797
This function converts a numeric value to a string. In this conversion
3798
the zero-fill flag of the field is taken into account.
3799
This is required so the resulting string value can be used instead of
3800
the field reference when propagating equalities.
3803
static void convert_zerofill_number_to_string(Item **item, Field_num *field)
3805
char buff[MAX_FIELD_WIDTH],*pos;
3806
String tmp(buff,sizeof(buff), field->charset()), *res;
3808
res= (*item)->val_str(&tmp);
3809
field->prepend_zeros(res);
3810
pos= (char *) sql_strmake (res->ptr(), res->length());
3811
*item= new Item_string(pos, res->length(), field->charset());
3816
Set a pointer to the multiple equality the field reference belongs to
3819
The function looks for a multiple equality containing the field item
3820
among those referenced by arg.
3821
In the case such equality exists the function does the following.
3822
If the found multiple equality contains a constant, then the field
3823
reference is substituted for this constant, otherwise it sets a pointer
3824
to the multiple equality in the field item.
3827
@param arg reference to list of multiple equalities where
3828
the field (this object) is to be looked for
3831
This function is supposed to be called as a callback parameter in calls
3832
of the compile method.
3835
- pointer to the replacing constant item, if the field item was substituted
3836
- pointer to the field item, otherwise.
3839
Item *Item_field::equal_fields_propagator(uchar *arg)
3843
item_equal= find_item_equal((COND_EQUAL *) arg);
3846
item= item_equal->get_const();
3848
Disable const propagation for items used in different comparison contexts.
3849
This must be done because, for example, Item_hex_string->val_int() is not
3850
the same as (Item_hex_string->val_str() in BINARY column)->val_int().
3851
We cannot simply disable the replacement in a particular context (
3852
e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
3853
Items don't know the context they are in and there are functions like
3854
IF (<hex_string>, 'yes', 'no').
3855
The same problem occurs when comparing a DATE/TIME field with a
3856
DATE/TIME represented as an int and as a string.
3859
(cmp_context != (Item_result)-1 && item->cmp_context != cmp_context))
3861
else if (field && (field->flags & ZEROFILL_FLAG) && IS_NUM(field->type()))
3863
if (item && cmp_context != INT_RESULT)
3864
convert_zerofill_number_to_string(&item, (Field_num *)field);
3873
Mark the item to not be part of substitution if it's not a binary item.
3875
See comments in Arg_comparator::set_compare_func() for details.
3878
bool Item_field::set_no_const_sub(uchar *arg)
3880
if (field->charset() != &my_charset_bin)
3887
Replace an Item_field for an equal Item_field that evaluated earlier
3890
The function returns a pointer to an item that is taken from
3891
the very beginning of the item_equal list which the Item_field
3892
object refers to (belongs to) unless item_equal contains a constant
3893
item. In this case the function returns this constant item,
3894
(if the substitution does not require conversion).
3895
If the Item_field object does not refer any Item_equal object
3896
'this' is returned .
3898
@param arg a dummy parameter, is not used here
3902
This function is supposed to be called as a callback parameter in calls
3903
of the thransformer method.
3906
- pointer to a replacement Item_field if there is a better equal item or
3907
a pointer to a constant equal item;
3911
Item *Item_field::replace_equal_field(uchar *arg)
3915
Item *const_item= item_equal->get_const();
3918
if (cmp_context != (Item_result)-1 &&
3919
const_item->cmp_context != cmp_context)
3923
Item_field *subst= item_equal->get_first();
3924
if (subst && !field->eq(subst->field))
3931
void Item::init_make_field(Send_field *tmp_field,
3932
enum enum_field_types field_type_arg)
3934
char *empty_name= (char*) "";
3935
tmp_field->db_name= empty_name;
3936
tmp_field->org_table_name= empty_name;
3937
tmp_field->org_col_name= empty_name;
3938
tmp_field->table_name= empty_name;
3939
tmp_field->col_name= name;
3940
tmp_field->charsetnr= collation.collation->number;
3941
tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
3942
(my_binary_compare(collation.collation) ?
3944
tmp_field->type= field_type_arg;
3945
tmp_field->length=max_length;
3946
tmp_field->decimals=decimals;
3948
tmp_field->flags |= UNSIGNED_FLAG;
3951
void Item::make_field(Send_field *tmp_field)
3953
init_make_field(tmp_field, field_type());
3957
enum_field_types Item::string_field_type() const
3959
enum_field_types f_type= MYSQL_TYPE_VAR_STRING;
3960
if (max_length >= 16777216)
3961
f_type= MYSQL_TYPE_LONG_BLOB;
3962
else if (max_length >= 65536)
3963
f_type= MYSQL_TYPE_MEDIUM_BLOB;
3968
void Item_empty_string::make_field(Send_field *tmp_field)
3970
init_make_field(tmp_field, string_field_type());
3974
enum_field_types Item::field_type() const
3976
switch (result_type()) {
3977
case STRING_RESULT: return string_field_type();
3978
case INT_RESULT: return MYSQL_TYPE_LONGLONG;
3979
case DECIMAL_RESULT: return MYSQL_TYPE_NEWDECIMAL;
3980
case REAL_RESULT: return MYSQL_TYPE_DOUBLE;
3984
return MYSQL_TYPE_VARCHAR;
3989
bool Item::is_datetime()
3991
switch (field_type())
3993
case MYSQL_TYPE_DATE:
3994
case MYSQL_TYPE_DATETIME:
3995
case MYSQL_TYPE_TIMESTAMP:
4004
String *Item::check_well_formed_result(String *str, bool send_error)
4006
/* Check whether we got a well-formed string */
4007
CHARSET_INFO *cs= str->charset();
4008
int well_formed_error;
4009
uint wlen= cs->cset->well_formed_len(cs,
4010
str->ptr(), str->ptr() + str->length(),
4011
str->length(), &well_formed_error);
4012
if (wlen < str->length())
4014
THD *thd= current_thd;
4016
enum MYSQL_ERROR::enum_warning_level level;
4017
uint diff= str->length() - wlen;
4018
set_if_smaller(diff, 3);
4019
octet2hex(hexbuf, str->ptr() + wlen, diff);
4022
my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
4023
cs->csname, hexbuf);
4027
level= MYSQL_ERROR::WARN_LEVEL_ERROR;
4031
push_warning_printf(thd, level, ER_INVALID_CHARACTER_STRING,
4032
ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
4038
Compare two items using a given collation
4042
item item to compare with
4043
binary_cmp TRUE <-> compare as binaries
4044
cs collation to use when comparing strings
4047
This method works exactly as Item::eq if the collation cs coincides with
4048
the collation of the compared objects. Otherwise, first the collations that
4049
differ from cs are replaced for cs and then the items are compared by
4050
Item::eq. After the comparison the original collations of items are
4054
1 compared items has been detected as equal
4058
bool Item::eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs)
4060
CHARSET_INFO *save_cs= 0;
4061
CHARSET_INFO *save_item_cs= 0;
4062
if (collation.collation != cs)
4064
save_cs= collation.collation;
4065
collation.collation= cs;
4067
if (item->collation.collation != cs)
4069
save_item_cs= item->collation.collation;
4070
item->collation.collation= cs;
4072
bool res= eq(item, binary_cmp);
4074
collation.collation= save_cs;
4076
item->collation.collation= save_item_cs;
4082
Create a field to hold a string value from an item.
4084
If max_length > CONVERT_IF_BIGGER_TO_BLOB create a blob @n
4085
If max_length > 0 create a varchar @n
4086
If max_length == 0 create a CHAR(0)
4088
@param table Table for which the field is created
4091
Field *Item::make_string_field(TABLE *table)
4094
DBUG_ASSERT(collation.collation);
4095
if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB)
4096
field= new Field_blob(max_length, maybe_null, name,
4097
collation.collation);
4098
/* Item_type_holder holds the exact type, do not change it */
4099
else if (max_length > 0 &&
4100
(type() != Item::TYPE_HOLDER || field_type() != MYSQL_TYPE_STRING))
4101
field= new Field_varstring(max_length, maybe_null, name, table->s,
4102
collation.collation);
4104
field= new Field_string(max_length, maybe_null, name,
4105
collation.collation);
4113
Create a field based on field_type of argument.
4115
For now, this is only used to create a field for
4116
IFNULL(x,something) and time functions
4124
Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length)
4127
The field functions defines a field to be not null if null_ptr is not 0
4129
uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
4132
switch (field_type()) {
4133
case MYSQL_TYPE_DECIMAL:
4134
case MYSQL_TYPE_NEWDECIMAL:
4135
field= new Field_new_decimal((uchar*) 0, max_length, null_ptr, 0,
4136
Field::NONE, name, decimals, 0,
4139
case MYSQL_TYPE_TINY:
4140
field= new Field_tiny((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4141
name, 0, unsigned_flag);
4143
case MYSQL_TYPE_SHORT:
4144
field= new Field_short((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4145
name, 0, unsigned_flag);
4147
case MYSQL_TYPE_LONG:
4148
field= new Field_long((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4149
name, 0, unsigned_flag);
4151
#ifdef HAVE_LONG_LONG
4152
case MYSQL_TYPE_LONGLONG:
4153
field= new Field_longlong((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4154
name, 0, unsigned_flag);
4157
case MYSQL_TYPE_FLOAT:
4158
field= new Field_float((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4159
name, decimals, 0, unsigned_flag);
4161
case MYSQL_TYPE_DOUBLE:
4162
field= new Field_double((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4163
name, decimals, 0, unsigned_flag);
4165
case MYSQL_TYPE_NULL:
4166
field= new Field_null((uchar*) 0, max_length, Field::NONE,
4167
name, &my_charset_bin);
4169
case MYSQL_TYPE_INT24:
4170
field= new Field_medium((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4171
name, 0, unsigned_flag);
4173
case MYSQL_TYPE_NEWDATE:
4174
case MYSQL_TYPE_DATE:
4175
field= new Field_newdate(maybe_null, name, &my_charset_bin);
4177
case MYSQL_TYPE_TIME:
4178
field= new Field_time(maybe_null, name, &my_charset_bin);
4180
case MYSQL_TYPE_TIMESTAMP:
4181
field= new Field_timestamp(maybe_null, name, &my_charset_bin);
4183
case MYSQL_TYPE_DATETIME:
4184
field= new Field_datetime(maybe_null, name, &my_charset_bin);
4186
case MYSQL_TYPE_YEAR:
4187
field= new Field_year((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
4190
case MYSQL_TYPE_BIT:
4191
field= new Field_bit_as_char(NULL, max_length, null_ptr, 0,
4195
/* This case should never be chosen */
4197
/* If something goes awfully wrong, it's better to get a string than die */
4198
case MYSQL_TYPE_STRING:
4199
if (fixed_length && max_length < CONVERT_IF_BIGGER_TO_BLOB)
4201
field= new Field_string(max_length, maybe_null, name,
4202
collation.collation);
4205
/* Fall through to make_string_field() */
4206
case MYSQL_TYPE_ENUM:
4207
case MYSQL_TYPE_SET:
4208
case MYSQL_TYPE_VAR_STRING:
4209
case MYSQL_TYPE_VARCHAR:
4210
return make_string_field(table);
4211
case MYSQL_TYPE_TINY_BLOB:
4212
case MYSQL_TYPE_MEDIUM_BLOB:
4213
case MYSQL_TYPE_LONG_BLOB:
4214
case MYSQL_TYPE_BLOB:
4215
if (this->type() == Item::TYPE_HOLDER)
4216
field= new Field_blob(max_length, maybe_null, name, collation.collation,
4219
field= new Field_blob(max_length, maybe_null, name, collation.collation);
4220
break; // Blob handled outside of case
4229
void Item_field::make_field(Send_field *tmp_field)
4231
field->make_field(tmp_field);
4232
DBUG_ASSERT(tmp_field->table_name != 0);
4234
tmp_field->col_name=name; // Use user supplied name
4236
tmp_field->table_name= table_name;
4238
tmp_field->db_name= db_name;
4243
Set a field's value from a item.
4246
void Item_field::save_org_in_field(Field *to)
4248
if (field->is_null())
4251
set_field_to_null_with_conversions(to, 1);
4256
field_conv(to,field);
4261
int Item_field::save_in_field(Field *to, bool no_conversions)
4264
DBUG_ENTER("Item_field::save_in_field");
4265
if (result_field->is_null())
4268
res= set_field_to_null_with_conversions(to, no_conversions);
4273
DBUG_EXECUTE("info", dbug_print(););
4274
res= field_conv(to,result_field);
4282
Store null in field.
4284
This is used on INSERT.
4285
Allow NULL to be inserted in timestamp and auto_increment values.
4287
@param field Field where we want to store NULL
4292
1 Field doesn't support NULL values and can't handle 'field = NULL'
4295
int Item_null::save_in_field(Field *field, bool no_conversions)
4297
return set_field_to_null_with_conversions(field, no_conversions);
4302
Store null in field.
4304
@param field Field where we want to store NULL
4309
1 Field doesn't support NULL values
4312
int Item_null::save_safe_in_field(Field *field)
4314
return set_field_to_null(field);
4319
This implementation can lose str_value content, so if the
4320
Item uses str_value to store something, it should
4321
reimplement it's ::save_in_field() as Item_string, for example, does
4324
int Item::save_in_field(Field *field, bool no_conversions)
4327
if (result_type() == STRING_RESULT)
4330
CHARSET_INFO *cs= collation.collation;
4331
char buff[MAX_FIELD_WIDTH]; // Alloc buffer for small columns
4332
str_value.set_quick(buff, sizeof(buff), cs);
4333
result=val_str(&str_value);
4336
str_value.set_quick(0, 0, cs);
4337
return set_field_to_null_with_conversions(field, no_conversions);
4340
/* NOTE: If null_value == FALSE, "result" must be not NULL. */
4342
field->set_notnull();
4343
error=field->store(result->ptr(),result->length(),cs);
4344
str_value.set_quick(0, 0, cs);
4346
else if (result_type() == REAL_RESULT &&
4347
field->result_type() == STRING_RESULT)
4349
double nr= val_real();
4351
return set_field_to_null_with_conversions(field, no_conversions);
4352
field->set_notnull();
4353
error= field->store(nr);
4355
else if (result_type() == REAL_RESULT)
4357
double nr= val_real();
4359
return set_field_to_null(field);
4360
field->set_notnull();
4361
error=field->store(nr);
4363
else if (result_type() == DECIMAL_RESULT)
4365
my_decimal decimal_value;
4366
my_decimal *value= val_decimal(&decimal_value);
4368
return set_field_to_null_with_conversions(field, no_conversions);
4369
field->set_notnull();
4370
error=field->store_decimal(value);
4374
longlong nr=val_int();
4376
return set_field_to_null_with_conversions(field, no_conversions);
4377
field->set_notnull();
4378
error=field->store(nr, unsigned_flag);
4384
int Item_string::save_in_field(Field *field, bool no_conversions)
4387
result=val_str(&str_value);
4388
return save_str_value_in_field(field, result);
4392
int Item_uint::save_in_field(Field *field, bool no_conversions)
4394
/* Item_int::save_in_field handles both signed and unsigned. */
4395
return Item_int::save_in_field(field, no_conversions);
4399
int Item_int::save_in_field(Field *field, bool no_conversions)
4401
longlong nr=val_int();
4403
return set_field_to_null(field);
4404
field->set_notnull();
4405
return field->store(nr, unsigned_flag);
4409
int Item_decimal::save_in_field(Field *field, bool no_conversions)
4411
field->set_notnull();
4412
return field->store_decimal(&decimal_value);
4416
bool Item_int::eq(const Item *arg, bool binary_cmp) const
4418
/* No need to check for null value as basic constant can't be NULL */
4419
if (arg->basic_const_item() && arg->type() == type())
4422
We need to cast off const to call val_int(). This should be OK for
4425
Item *item= (Item*) arg;
4426
return item->val_int() == value && item->unsigned_flag == unsigned_flag;
4432
Item *Item_int_with_ref::clone_item()
4434
DBUG_ASSERT(ref->const_item());
4436
We need to evaluate the constant to make sure it works with
4439
return (ref->unsigned_flag ?
4440
new Item_uint(ref->name, ref->val_int(), ref->max_length) :
4441
new Item_int(ref->name, ref->val_int(), ref->max_length));
4445
Item_num *Item_uint::neg()
4447
Item_decimal *item= new Item_decimal(value, 1);
4452
static uint nr_of_decimals(const char *str, const char *end)
4454
const char *decimal_point;
4456
/* Find position for '.' */
4461
if (*str == 'e' || *str == 'E')
4462
return NOT_FIXED_DEC;
4467
for (; my_isdigit(system_charset_info, *str) ; str++)
4469
if (*str == 'e' || *str == 'E')
4470
return NOT_FIXED_DEC;
4471
return (uint) (str - decimal_point);
4476
This function is only called during parsing. We will signal an error if
4477
value is not a true double value (overflow)
4480
Item_float::Item_float(const char *str_arg, uint length)
4484
value= my_strntod(&my_charset_bin, (char*) str_arg, length, &end_not_used,
4489
Note that we depend on that str_arg is null terminated, which is true
4490
when we are in the parser
4492
DBUG_ASSERT(str_arg[length] == 0);
4493
my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", (char*) str_arg);
4495
presentation= name=(char*) str_arg;
4496
decimals=(uint8) nr_of_decimals(str_arg, str_arg+length);
4502
int Item_float::save_in_field(Field *field, bool no_conversions)
4504
double nr= val_real();
4506
return set_field_to_null(field);
4507
field->set_notnull();
4508
return field->store(nr);
4512
void Item_float::print(String *str, enum_query_type query_type)
4516
str->append(presentation);
4520
String num(buffer, sizeof(buffer), &my_charset_bin);
4521
num.set_real(value, decimals, &my_charset_bin);
4528
In string context this is a binary string.
4529
In number context this is a longlong value.
4532
bool Item_float::eq(const Item *arg, bool binary_cmp) const
4534
if (arg->basic_const_item() && arg->type() == type())
4537
We need to cast off const to call val_int(). This should be OK for
4540
Item *item= (Item*) arg;
4541
return item->val_real() == value;
4547
inline uint char_val(char X)
4549
return (uint) (X >= '0' && X <= '9' ? X-'0' :
4550
X >= 'A' && X <= 'Z' ? X-'A'+10 :
4555
Item_hex_string::Item_hex_string(const char *str, uint str_length)
4557
max_length=(str_length+1)/2;
4558
char *ptr=(char*) sql_alloc(max_length+1);
4561
str_value.set(ptr,max_length,&my_charset_bin);
4562
char *end=ptr+max_length;
4563
if (max_length*2 != str_length)
4564
*ptr++=char_val(*str++); // Not even, assume 0 prefix
4567
*ptr++= (char) (char_val(str[0])*16+char_val(str[1]));
4570
*ptr=0; // Keep purify happy
4571
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
4576
longlong Item_hex_string::val_int()
4578
// following assert is redundant, because fixed=1 assigned in constructor
4579
DBUG_ASSERT(fixed == 1);
4580
char *end=(char*) str_value.ptr()+str_value.length(),
4581
*ptr=end-min(str_value.length(),sizeof(longlong));
4584
for (; ptr != end ; ptr++)
4585
value=(value << 8)+ (ulonglong) (uchar) *ptr;
4586
return (longlong) value;
4590
my_decimal *Item_hex_string::val_decimal(my_decimal *decimal_value)
4592
// following assert is redundant, because fixed=1 assigned in constructor
4593
DBUG_ASSERT(fixed == 1);
4594
ulonglong value= (ulonglong)val_int();
4595
int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value);
4596
return (decimal_value);
4600
int Item_hex_string::save_in_field(Field *field, bool no_conversions)
4602
field->set_notnull();
4603
if (field->result_type() == STRING_RESULT)
4604
return field->store(str_value.ptr(), str_value.length(),
4605
collation.collation);
4608
uint32 length= str_value.length();
4611
nr= field->flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX;
4614
nr= (ulonglong) val_int();
4615
if ((length == 8) && !(field->flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX))
4620
return field->store((longlong) nr, TRUE); // Assume hex numbers are unsigned
4623
if (!field->store((longlong) nr, TRUE))
4624
field->set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE,
4630
void Item_hex_string::print(String *str, enum_query_type query_type)
4632
char *end= (char*) str_value.ptr() + str_value.length(),
4633
*ptr= end - min(str_value.length(), sizeof(longlong));
4635
for (; ptr != end ; ptr++)
4637
str->append(_dig_vec_lower[((uchar) *ptr) >> 4]);
4638
str->append(_dig_vec_lower[((uchar) *ptr) & 0x0F]);
4643
bool Item_hex_string::eq(const Item *arg, bool binary_cmp) const
4645
if (arg->basic_const_item() && arg->type() == type())
4648
return !stringcmp(&str_value, &arg->str_value);
4649
return !sortcmp(&str_value, &arg->str_value, collation.collation);
4655
Item *Item_hex_string::safe_charset_converter(CHARSET_INFO *tocs)
4658
String tmp, *str= val_str(&tmp);
4660
if (!(conv= new Item_string(str->ptr(), str->length(), tocs)))
4662
conv->str_value.copy();
4663
conv->str_value.mark_as_const();
4670
In string context this is a binary string.
4671
In number context this is a longlong value.
4674
Item_bin_string::Item_bin_string(const char *str, uint str_length)
4676
const char *end= str + str_length - 1;
4680
max_length= (str_length + 7) >> 3;
4681
char *ptr= (char*) sql_alloc(max_length + 1);
4684
str_value.set(ptr, max_length, &my_charset_bin);
4685
ptr+= max_length - 1;
4686
ptr[1]= 0; // Set end null for string
4687
for (; end >= str; end--)
4700
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
4706
Pack data in buffer for sending.
4709
bool Item_null::send(Protocol *protocol, String *packet)
4711
return protocol->store_null();
4715
This is only called from items that is not of type item_field.
4718
bool Item::send(Protocol *protocol, String *buffer)
4721
enum_field_types f_type;
4723
switch ((f_type=field_type())) {
4725
case MYSQL_TYPE_NULL:
4726
case MYSQL_TYPE_DECIMAL:
4727
case MYSQL_TYPE_ENUM:
4728
case MYSQL_TYPE_SET:
4729
case MYSQL_TYPE_TINY_BLOB:
4730
case MYSQL_TYPE_MEDIUM_BLOB:
4731
case MYSQL_TYPE_LONG_BLOB:
4732
case MYSQL_TYPE_BLOB:
4733
case MYSQL_TYPE_STRING:
4734
case MYSQL_TYPE_VAR_STRING:
4735
case MYSQL_TYPE_VARCHAR:
4736
case MYSQL_TYPE_BIT:
4737
case MYSQL_TYPE_NEWDECIMAL:
4740
if ((res=val_str(buffer)))
4741
result= protocol->store(res->ptr(),res->length(),res->charset());
4744
case MYSQL_TYPE_TINY:
4749
result= protocol->store_tiny(nr);
4752
case MYSQL_TYPE_SHORT:
4753
case MYSQL_TYPE_YEAR:
4758
result= protocol->store_short(nr);
4761
case MYSQL_TYPE_INT24:
4762
case MYSQL_TYPE_LONG:
4767
result= protocol->store_long(nr);
4770
case MYSQL_TYPE_LONGLONG:
4775
result= protocol->store_longlong(nr, unsigned_flag);
4778
case MYSQL_TYPE_FLOAT:
4781
nr= (float) val_real();
4783
result= protocol->store(nr, decimals, buffer);
4786
case MYSQL_TYPE_DOUBLE:
4788
double nr= val_real();
4790
result= protocol->store(nr, decimals, buffer);
4793
case MYSQL_TYPE_DATETIME:
4794
case MYSQL_TYPE_DATE:
4795
case MYSQL_TYPE_TIMESTAMP:
4798
get_date(&tm, TIME_FUZZY_DATE);
4801
if (f_type == MYSQL_TYPE_DATE)
4802
return protocol->store_date(&tm);
4804
result= protocol->store(&tm);
4808
case MYSQL_TYPE_TIME:
4813
result= protocol->store_time(&tm);
4818
result= protocol->store_null();
4823
bool Item_field::send(Protocol *protocol, String *buffer)
4825
return protocol->store(result_field);
4829
void Item_field::update_null_value()
4832
need to set no_errors to prevent warnings about type conversion
4835
THD *thd= field->table->in_use;
4838
no_errors= thd->no_errors;
4840
Item::update_null_value();
4841
thd->no_errors= no_errors;
4846
Add the field to the select list and substitute it for the reference to
4850
Item_field::update_value_transformer()
4851
select_arg current select
4854
If the field doesn't belong to the table being inserted into then it is
4855
added to the select list, pointer to it is stored in the ref_pointer_array
4856
of the select and the field itself is substituted for the Item_ref object.
4857
This is done in order to get correct values from update fields that
4858
belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY
4863
ref if all conditions are met
4864
this field otherwise
4867
Item *Item_field::update_value_transformer(uchar *select_arg)
4869
SELECT_LEX *select= (SELECT_LEX*)select_arg;
4872
if (field->table != select->context.table_list->table &&
4873
type() != Item::TRIGGER_FIELD_ITEM)
4875
List<Item> *all_fields= &select->join->all_fields;
4876
Item **ref_pointer_array= select->ref_pointer_array;
4877
int el= all_fields->elements;
4880
ref_pointer_array[el]= (Item*)this;
4881
all_fields->push_front((Item*)this);
4882
ref= new Item_ref(&select->context, ref_pointer_array + el,
4883
table_name, field_name);
4890
void Item_field::print(String *str, enum_query_type query_type)
4892
if (field && field->table->const_table)
4894
char buff[MAX_FIELD_WIDTH];
4895
String tmp(buff,sizeof(buff),str->charset());
4896
field->val_str(&tmp);
4902
Item_ident::print(str, query_type);
4906
Item_ref::Item_ref(Name_resolution_context *context_arg,
4907
Item **item, const char *table_name_arg,
4908
const char *field_name_arg,
4909
bool alias_name_used_arg)
4910
:Item_ident(context_arg, NullS, table_name_arg, field_name_arg),
4911
result_field(0), ref(item)
4913
alias_name_used= alias_name_used_arg;
4915
This constructor used to create some internals references over fixed items
4917
if (ref && *ref && (*ref)->fixed)
4923
Resolve the name of a reference to a column reference.
4925
The method resolves the column reference represented by 'this' as a column
4926
present in one of: GROUP BY clause, SELECT clause, outer queries. It is
4927
used typically for columns in the HAVING clause which are not under
4928
aggregate functions.
4931
Item_ref::ref is 0 or points to a valid item.
4934
The name resolution algorithm used is (where [T_j] is an optional table
4935
name that qualifies the column name):
4938
resolve_extended([T_j].col_ref_i)
4940
Search for a column or derived column named col_ref_i [in table T_j]
4941
in the SELECT and GROUP clauses of Q.
4943
if such a column is NOT found AND // Lookup in outer queries.
4944
there are outer queries
4946
for each outer query Q_k beginning from the inner-most one
4948
Search for a column or derived column named col_ref_i
4949
[in table T_j] in the SELECT and GROUP clauses of Q_k.
4951
if such a column is not found AND
4952
- Q_k is not a group query AND
4953
- Q_k is not inside an aggregate function
4955
- Q_(k-1) is not in a HAVING or SELECT clause of Q_k
4957
search for a column or derived column named col_ref_i
4958
[in table T_j] in the FROM clause of Q_k;
4965
This procedure treats GROUP BY and SELECT clauses as one namespace for
4966
column references in HAVING. Notice that compared to
4967
Item_field::fix_fields, here we first search the SELECT and GROUP BY
4968
clauses, and then we search the FROM clause.
4970
@param[in] thd current thread
4971
@param[in,out] reference view column if this item was resolved to a
4975
Here we could first find the field anyway, and then test this
4976
condition, so that we can give a better error message -
4977
ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
4978
ER_BAD_FIELD_ERROR which we produce now.
4986
bool Item_ref::fix_fields(THD *thd, Item **reference)
4988
enum_parsing_place place= NO_MATTER;
4989
DBUG_ASSERT(fixed == 0);
4990
SELECT_LEX *current_sel= thd->lex->current_select;
4992
if (!ref || ref == not_found_item)
4994
if (!(ref= resolve_ref_in_select_and_group(thd, this,
4995
context->select_lex)))
4996
goto error; /* Some error occurred (e.g. ambiguous names). */
4998
if (ref == not_found_item) /* This reference was not resolved. */
5000
Name_resolution_context *last_checked_context= context;
5001
Name_resolution_context *outer_context= context->outer_context;
5007
/* The current reference cannot be resolved in this query. */
5008
my_error(ER_BAD_FIELD_ERROR,MYF(0),
5009
this->full_name(), current_thd->where);
5014
If there is an outer context (select), and it is not a derived table
5015
(which do not support the use of outer fields for now), try to
5016
resolve this reference in the outer select(s).
5018
We treat each subselect as a separate namespace, so that different
5019
subselects may contain columns with the same names. The subselects are
5020
searched starting from the innermost.
5022
from_field= (Field*) not_found_field;
5026
SELECT_LEX *select= outer_context->select_lex;
5027
Item_subselect *prev_subselect_item=
5028
last_checked_context->select_lex->master_unit()->item;
5029
last_checked_context= outer_context;
5031
/* Search in the SELECT and GROUP lists of the outer select. */
5032
if (outer_context->resolve_in_select_list)
5034
if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
5035
goto error; /* Some error occurred (e.g. ambiguous names). */
5036
if (ref != not_found_item)
5038
DBUG_ASSERT(*ref && (*ref)->fixed);
5039
prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
5040
prev_subselect_item->const_item_cache&= (*ref)->const_item();
5044
Set ref to 0 to ensure that we get an error in case we replaced
5045
this item with another item and still use this item in some
5046
other place of the parse tree.
5051
place= prev_subselect_item->parsing_place;
5053
Check table fields only if the subquery is used somewhere out of
5054
HAVING or the outer SELECT does not use grouping (i.e. tables are
5057
Here we could first find the field anyway, and then test this
5058
condition, so that we can give a better error message -
5059
ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
5060
ER_BAD_FIELD_ERROR which we produce now.
5062
if ((place != IN_HAVING ||
5063
(!select->with_sum_func &&
5064
select->group_list.elements == 0)))
5067
In case of view, find_field_in_tables() write pointer to view
5068
field expression to 'reference', i.e. it substitute that
5069
expression instead of this Item_ref
5071
from_field= find_field_in_tables(thd, this,
5073
first_name_resolution_table,
5075
last_name_resolution_table,
5077
IGNORE_EXCEPT_NON_UNIQUE,
5081
if (from_field == view_ref_found)
5083
Item::Type refer_type= (*reference)->type();
5084
prev_subselect_item->used_tables_cache|=
5085
(*reference)->used_tables();
5086
prev_subselect_item->const_item_cache&=
5087
(*reference)->const_item();
5088
DBUG_ASSERT((*reference)->type() == REF_ITEM);
5089
mark_as_dependent(thd, last_checked_context->select_lex,
5090
context->select_lex, this,
5091
((refer_type == REF_ITEM ||
5092
refer_type == FIELD_ITEM) ?
5093
(Item_ident*) (*reference) :
5096
view reference found, we substituted it instead of this
5101
if (from_field != not_found_field)
5103
if (cached_table && cached_table->select_lex &&
5104
outer_context->select_lex &&
5105
cached_table->select_lex != outer_context->select_lex)
5108
Due to cache, find_field_in_tables() can return field which
5109
doesn't belong to provided outer_context. In this case we have
5110
to find proper field context in order to fix field correcly.
5114
outer_context= outer_context->outer_context;
5115
select= outer_context->select_lex;
5116
prev_subselect_item=
5117
last_checked_context->select_lex->master_unit()->item;
5118
last_checked_context= outer_context;
5119
} while (outer_context && outer_context->select_lex &&
5120
cached_table->select_lex != outer_context->select_lex);
5122
prev_subselect_item->used_tables_cache|= from_field->table->map;
5123
prev_subselect_item->const_item_cache= 0;
5127
DBUG_ASSERT(from_field == not_found_field);
5129
/* Reference is not found => depend on outer (or just error). */
5130
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
5131
prev_subselect_item->const_item_cache= 0;
5133
outer_context= outer_context->outer_context;
5134
} while (outer_context);
5136
DBUG_ASSERT(from_field != 0 && from_field != view_ref_found);
5137
if (from_field != not_found_field)
5140
if (!(fld= new Item_field(from_field)))
5142
thd->change_item_tree(reference, fld);
5143
mark_as_dependent(thd, last_checked_context->select_lex,
5144
thd->lex->current_select, this, fld);
5146
A reference is resolved to a nest level that's outer or the same as
5147
the nest level of the enclosing set function : adjust the value of
5148
max_arg_level for the function if it's needed.
5150
if (thd->lex->in_sum_func &&
5151
thd->lex->in_sum_func->nest_level >=
5152
last_checked_context->select_lex->nest_level)
5153
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5154
last_checked_context->select_lex->nest_level);
5159
/* The item was not a table field and not a reference */
5160
my_error(ER_BAD_FIELD_ERROR, MYF(0),
5161
this->full_name(), current_thd->where);
5164
/* Should be checked in resolve_ref_in_select_and_group(). */
5165
DBUG_ASSERT(*ref && (*ref)->fixed);
5166
mark_as_dependent(thd, last_checked_context->select_lex,
5167
context->select_lex, this, this);
5169
A reference is resolved to a nest level that's outer or the same as
5170
the nest level of the enclosing set function : adjust the value of
5171
max_arg_level for the function if it's needed.
5173
if (thd->lex->in_sum_func &&
5174
thd->lex->in_sum_func->nest_level >=
5175
last_checked_context->select_lex->nest_level)
5176
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5177
last_checked_context->select_lex->nest_level);
5183
Check if this is an incorrect reference in a group function or forward
5184
reference. Do not issue an error if this is:
5185
1. outer reference (will be fixed later by the fix_inner_refs function);
5186
2. an unnamed reference inside an aggregate function.
5188
if (!((*ref)->type() == REF_ITEM &&
5189
((Item_ref *)(*ref))->ref_type() == OUTER_REF) &&
5190
(((*ref)->with_sum_func && name &&
5191
!(current_sel->linkage != GLOBAL_OPTIONS_TYPE &&
5192
current_sel->having_fix_field)) ||
5195
my_error(ER_ILLEGAL_REFERENCE, MYF(0),
5196
name, ((*ref)->with_sum_func?
5197
"reference to group function":
5198
"forward reference in item list"));
5204
if ((*ref)->check_cols(1))
5209
context->process_error(thd);
5214
void Item_ref::set_properties()
5216
max_length= (*ref)->max_length;
5217
maybe_null= (*ref)->maybe_null;
5218
decimals= (*ref)->decimals;
5219
collation.set((*ref)->collation);
5221
We have to remember if we refer to a sum function, to ensure that
5222
split_sum_func() doesn't try to change the reference.
5224
with_sum_func= (*ref)->with_sum_func;
5225
unsigned_flag= (*ref)->unsigned_flag;
5227
if (alias_name_used)
5229
if ((*ref)->type() == FIELD_ITEM)
5230
alias_name_used= ((Item_ident *) (*ref))->alias_name_used;
5232
alias_name_used= TRUE; // it is not field, so it is was resolved by alias
5236
void Item_ref::cleanup()
5238
DBUG_ENTER("Item_ref::cleanup");
5239
Item_ident::cleanup();
5245
void Item_ref::print(String *str, enum_query_type query_type)
5249
if ((*ref)->type() != Item::CACHE_ITEM && ref_type() != VIEW_REF &&
5250
!table_name && name && alias_name_used)
5252
THD *thd= current_thd;
5253
append_identifier(thd, str, name, (uint) strlen(name));
5256
(*ref)->print(str, query_type);
5259
Item_ident::print(str, query_type);
5263
bool Item_ref::send(Protocol *prot, String *tmp)
5266
return prot->store(result_field);
5267
return (*ref)->send(prot, tmp);
5271
double Item_ref::val_result()
5275
if ((null_value= result_field->is_null()))
5277
return result_field->val_real();
5283
longlong Item_ref::val_int_result()
5287
if ((null_value= result_field->is_null()))
5289
return result_field->val_int();
5295
String *Item_ref::str_result(String* str)
5299
if ((null_value= result_field->is_null()))
5301
str->set_charset(str_value.charset());
5302
return result_field->val_str(str, &str_value);
5304
return val_str(str);
5308
my_decimal *Item_ref::val_decimal_result(my_decimal *decimal_value)
5312
if ((null_value= result_field->is_null()))
5314
return result_field->val_decimal(decimal_value);
5316
return val_decimal(decimal_value);
5320
bool Item_ref::val_bool_result()
5324
if ((null_value= result_field->is_null()))
5326
switch (result_field->result_type()) {
5328
return result_field->val_int() != 0;
5329
case DECIMAL_RESULT:
5331
my_decimal decimal_value;
5332
my_decimal *val= result_field->val_decimal(&decimal_value);
5334
return !my_decimal_is_zero(val);
5339
return result_field->val_real() != 0.0;
5349
double Item_ref::val_real()
5352
double tmp=(*ref)->val_result();
5353
null_value=(*ref)->null_value;
5358
longlong Item_ref::val_int()
5361
longlong tmp=(*ref)->val_int_result();
5362
null_value=(*ref)->null_value;
5367
bool Item_ref::val_bool()
5370
bool tmp= (*ref)->val_bool_result();
5371
null_value= (*ref)->null_value;
5376
String *Item_ref::val_str(String* tmp)
5379
tmp=(*ref)->str_result(tmp);
5380
null_value=(*ref)->null_value;
5385
bool Item_ref::is_null()
5388
return (*ref)->is_null();
5392
bool Item_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
5394
return (null_value=(*ref)->get_date_result(ltime,fuzzydate));
5398
my_decimal *Item_ref::val_decimal(my_decimal *decimal_value)
5400
my_decimal *val= (*ref)->val_decimal_result(decimal_value);
5401
null_value= (*ref)->null_value;
5405
int Item_ref::save_in_field(Field *to, bool no_conversions)
5408
DBUG_ASSERT(!result_field);
5409
res= (*ref)->save_in_field(to, no_conversions);
5410
null_value= (*ref)->null_value;
5415
void Item_ref::save_org_in_field(Field *field)
5417
(*ref)->save_org_in_field(field);
5421
void Item_ref::make_field(Send_field *field)
5423
(*ref)->make_field(field);
5424
/* Non-zero in case of a view */
5426
field->col_name= name;
5428
field->table_name= table_name;
5430
field->db_name= db_name;
5434
Item *Item_ref::get_tmp_table_item(THD *thd)
5437
return (*ref)->get_tmp_table_item(thd);
5439
Item_field *item= new Item_field(result_field);
5442
item->table_name= table_name;
5443
item->db_name= db_name;
5449
void Item_ref_null_helper::print(String *str, enum_query_type query_type)
5451
str->append(STRING_WITH_LEN("<ref_null_helper>("));
5453
(*ref)->print(str, query_type);
5460
double Item_direct_ref::val_real()
5462
double tmp=(*ref)->val_real();
5463
null_value=(*ref)->null_value;
5468
longlong Item_direct_ref::val_int()
5470
longlong tmp=(*ref)->val_int();
5471
null_value=(*ref)->null_value;
5476
String *Item_direct_ref::val_str(String* tmp)
5478
tmp=(*ref)->val_str(tmp);
5479
null_value=(*ref)->null_value;
5484
my_decimal *Item_direct_ref::val_decimal(my_decimal *decimal_value)
5486
my_decimal *tmp= (*ref)->val_decimal(decimal_value);
5487
null_value=(*ref)->null_value;
5492
bool Item_direct_ref::val_bool()
5494
bool tmp= (*ref)->val_bool();
5495
null_value=(*ref)->null_value;
5500
bool Item_direct_ref::is_null()
5502
return (*ref)->is_null();
5506
bool Item_direct_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
5508
return (null_value=(*ref)->get_date(ltime,fuzzydate));
5513
Prepare referenced field then call usual Item_direct_ref::fix_fields .
5515
@param thd thread handler
5516
@param reference reference on reference where this item stored
5524
bool Item_direct_view_ref::fix_fields(THD *thd, Item **reference)
5526
/* view fild reference must be defined */
5528
/* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */
5529
if (!(*ref)->fixed &&
5530
((*ref)->fix_fields(thd, ref)))
5532
return Item_direct_ref::fix_fields(thd, reference);
5536
Prepare referenced outer field then call usual Item_direct_ref::fix_fields
5539
Item_outer_ref::fix_fields()
5541
reference reference on reference where this item stored
5548
bool Item_outer_ref::fix_fields(THD *thd, Item **reference)
5551
/* outer_ref->check_cols() will be made in Item_direct_ref::fix_fields */
5552
if ((*ref) && !(*ref)->fixed && ((*ref)->fix_fields(thd, reference)))
5554
err= Item_direct_ref::fix_fields(thd, reference);
5557
if ((*ref)->type() == Item::FIELD_ITEM)
5558
table_name= ((Item_field*)outer_ref)->table_name;
5562
void Item_outer_ref::fix_after_pullout(st_select_lex *new_parent, Item **ref)
5564
if (depended_from == new_parent)
5567
outer_ref->fix_after_pullout(new_parent, ref);
5571
void Item_ref::fix_after_pullout(st_select_lex *new_parent, Item **refptr)
5573
if (depended_from == new_parent)
5575
(*ref)->fix_after_pullout(new_parent, ref);
5576
depended_from= NULL;
5581
Compare two view column references for equality.
5583
A view column reference is considered equal to another column
5584
reference if the second one is a view column and if both column
5585
references resolve to the same item. It is assumed that both
5586
items are of the same type.
5588
@param item item to compare with
5589
@param binary_cmp make binary comparison
5592
TRUE Referenced item is equal to given item
5597
bool Item_direct_view_ref::eq(const Item *item, bool binary_cmp) const
5599
if (item->type() == REF_ITEM)
5601
Item_ref *item_ref= (Item_ref*) item;
5602
if (item_ref->ref_type() == VIEW_REF)
5604
Item *item_ref_ref= *(item_ref->ref);
5605
return ((*ref)->real_item() == item_ref_ref->real_item());
5611
bool Item_default_value::eq(const Item *item, bool binary_cmp) const
5613
return item->type() == DEFAULT_VALUE_ITEM &&
5614
((Item_default_value *)item)->arg->eq(arg, binary_cmp);
5618
bool Item_default_value::fix_fields(THD *thd, Item **items)
5621
Item_field *field_arg;
5623
DBUG_ASSERT(fixed == 0);
5630
if (!arg->fixed && arg->fix_fields(thd, &arg))
5634
real_arg= arg->real_item();
5635
if (real_arg->type() != FIELD_ITEM)
5637
my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->name);
5641
field_arg= (Item_field *)real_arg;
5642
if (field_arg->field->flags & NO_DEFAULT_VALUE_FLAG)
5644
my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), field_arg->field->field_name);
5647
if (!(def_field= (Field*) sql_alloc(field_arg->field->size_of())))
5649
memcpy(def_field, field_arg->field, field_arg->field->size_of());
5650
def_field->move_field_offset((my_ptrdiff_t)
5651
(def_field->table->s->default_values -
5652
def_field->table->record[0]));
5653
set_field(def_field);
5657
context->process_error(thd);
5662
void Item_default_value::print(String *str, enum_query_type query_type)
5666
str->append(STRING_WITH_LEN("default"));
5669
str->append(STRING_WITH_LEN("default("));
5670
arg->print(str, query_type);
5675
int Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
5679
if (field_arg->flags & NO_DEFAULT_VALUE_FLAG)
5681
if (field_arg->reset())
5683
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
5684
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
5689
push_warning_printf(field_arg->table->in_use,
5690
MYSQL_ERROR::WARN_LEVEL_WARN,
5691
ER_NO_DEFAULT_FOR_FIELD,
5692
ER(ER_NO_DEFAULT_FOR_FIELD),
5693
field_arg->field_name);
5697
field_arg->set_default();
5700
return Item_field::save_in_field(field_arg, no_conversions);
5705
This method like the walk method traverses the item tree, but at the
5706
same time it can replace some nodes in the tree.
5709
Item *Item_default_value::transform(Item_transformer transformer, uchar *args)
5711
Item *new_item= arg->transform(transformer, args);
5716
THD::change_item_tree() should be called only if the tree was
5717
really transformed, i.e. when a new item has been created.
5718
Otherwise we'll be allocating a lot of unnecessary memory for
5719
change records at each execution.
5721
if (arg != new_item)
5722
current_thd->change_item_tree(&arg, new_item);
5723
return (this->*transformer)(args);
5727
bool Item_insert_value::eq(const Item *item, bool binary_cmp) const
5729
return item->type() == INSERT_VALUE_ITEM &&
5730
((Item_default_value *)item)->arg->eq(arg, binary_cmp);
5734
bool Item_insert_value::fix_fields(THD *thd, Item **items)
5736
DBUG_ASSERT(fixed == 0);
5737
/* We should only check that arg is in first table */
5741
TABLE_LIST *orig_next_table= context->last_name_resolution_table;
5742
context->last_name_resolution_table= context->first_name_resolution_table;
5743
res= arg->fix_fields(thd, &arg);
5744
context->last_name_resolution_table= orig_next_table;
5749
if (arg->type() == REF_ITEM)
5751
Item_ref *ref= (Item_ref *)arg;
5752
if (ref->ref[0]->type() != FIELD_ITEM)
5754
my_error(ER_BAD_FIELD_ERROR, MYF(0), "", "VALUES() function");
5760
According to our SQL grammar, VALUES() function can reference
5763
DBUG_ASSERT(arg->type() == FIELD_ITEM);
5765
Item_field *field_arg= (Item_field *)arg;
5767
if (field_arg->field->table->insert_values)
5769
Field *def_field= (Field*) sql_alloc(field_arg->field->size_of());
5772
memcpy(def_field, field_arg->field, field_arg->field->size_of());
5773
def_field->move_field_offset((my_ptrdiff_t)
5774
(def_field->table->insert_values -
5775
def_field->table->record[0]));
5776
set_field(def_field);
5780
Field *tmp_field= field_arg->field;
5781
/* charset doesn't matter here, it's to avoid sigsegv only */
5782
tmp_field= new Field_null(0, 0, Field::NONE, field_arg->field->field_name,
5786
tmp_field->init(field_arg->field->table);
5787
set_field(tmp_field);
5793
void Item_insert_value::print(String *str, enum_query_type query_type)
5795
str->append(STRING_WITH_LEN("values("));
5796
arg->print(str, query_type);
5801
Item_result item_cmp_type(Item_result a,Item_result b)
5803
if (a == STRING_RESULT && b == STRING_RESULT)
5804
return STRING_RESULT;
5805
if (a == INT_RESULT && b == INT_RESULT)
5807
else if (a == ROW_RESULT || b == ROW_RESULT)
5809
if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
5810
(b == INT_RESULT || b == DECIMAL_RESULT))
5811
return DECIMAL_RESULT;
5816
void resolve_const_item(THD *thd, Item **ref, Item *comp_item)
5819
Item *new_item= NULL;
5820
if (item->basic_const_item())
5821
return; // Can't be better
5822
Item_result res_type=item_cmp_type(comp_item->result_type(),
5823
item->result_type());
5824
char *name=item->name; // Alloced by sql_alloc
5829
char buff[MAX_FIELD_WIDTH];
5830
String tmp(buff,sizeof(buff),&my_charset_bin),*result;
5831
result=item->val_str(&tmp);
5832
if (item->null_value)
5833
new_item= new Item_null(name);
5836
uint length= result->length();
5837
char *tmp_str= sql_strmake(result->ptr(), length);
5838
new_item= new Item_string(name, tmp_str, length, result->charset());
5844
longlong result=item->val_int();
5845
uint length=item->max_length;
5846
bool null_value=item->null_value;
5847
new_item= (null_value ? (Item*) new Item_null(name) :
5848
(Item*) new Item_int(name, result, length));
5852
if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
5855
Substitute constants only in Item_rows. Don't affect other Items
5856
with ROW_RESULT (eg Item_singlerow_subselect).
5858
For such Items more optimal is to detect if it is constant and replace
5859
it with Item_row. This would optimize queries like this:
5860
SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
5862
Item_row *item_row= (Item_row*) item;
5863
Item_row *comp_item_row= (Item_row*) comp_item;
5867
If item and comp_item are both Item_rows and have same number of cols
5868
then process items in Item_row one by one.
5869
We can't ignore NULL values here as this item may be used with <=>, in
5870
which case NULL's are significant.
5872
DBUG_ASSERT(item->result_type() == comp_item->result_type());
5873
DBUG_ASSERT(item_row->cols() == comp_item_row->cols());
5874
col= item_row->cols();
5876
resolve_const_item(thd, item_row->addr(col),
5877
comp_item_row->element_index(col));
5882
{ // It must REAL_RESULT
5883
double result= item->val_real();
5884
uint length=item->max_length,decimals=item->decimals;
5885
bool null_value=item->null_value;
5886
new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
5887
new Item_float(name, result, decimals, length));
5890
case DECIMAL_RESULT:
5892
my_decimal decimal_value;
5893
my_decimal *result= item->val_decimal(&decimal_value);
5894
uint length= item->max_length, decimals= item->decimals;
5895
bool null_value= item->null_value;
5896
new_item= (null_value ?
5897
(Item*) new Item_null(name) :
5898
(Item*) new Item_decimal(name, result, length, decimals));
5905
thd->change_item_tree(ref, new_item);
5909
Return true if the value stored in the field is equal to the const
5912
We need to use this on the range optimizer because in some cases
5913
we can't store the value in the field without some precision/character loss.
5916
bool field_is_equal_to_item(Field *field,Item *item)
5919
Item_result res_type=item_cmp_type(field->result_type(),
5920
item->result_type());
5921
if (res_type == STRING_RESULT)
5923
char item_buff[MAX_FIELD_WIDTH];
5924
char field_buff[MAX_FIELD_WIDTH];
5925
String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result;
5926
String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
5927
item_result=item->val_str(&item_tmp);
5928
if (item->null_value)
5929
return 1; // This must be true
5930
field->val_str(&field_tmp);
5931
return !stringcmp(&field_tmp,item_result);
5933
if (res_type == INT_RESULT)
5934
return 1; // Both where of type int
5935
if (res_type == DECIMAL_RESULT)
5937
my_decimal item_buf, *item_val,
5938
field_buf, *field_val;
5939
item_val= item->val_decimal(&item_buf);
5940
if (item->null_value)
5941
return 1; // This must be true
5942
field_val= field->val_decimal(&field_buf);
5943
return !my_decimal_cmp(item_val, field_val);
5945
double result= item->val_real();
5946
if (item->null_value)
5948
return result == field->val_real();
5951
Item_cache* Item_cache::get_cache(const Item *item)
5953
switch (item->result_type()) {
5955
return new Item_cache_int();
5957
return new Item_cache_real();
5958
case DECIMAL_RESULT:
5959
return new Item_cache_decimal();
5961
return new Item_cache_str(item);
5963
return new Item_cache_row();
5965
// should never be in real life
5972
void Item_cache::print(String *str, enum_query_type query_type)
5974
str->append(STRING_WITH_LEN("<cache>("));
5976
example->print(str, query_type);
5978
Item::print(str, query_type);
5983
void Item_cache_int::store(Item *item)
5985
value= item->val_int_result();
5986
null_value= item->null_value;
5987
unsigned_flag= item->unsigned_flag;
5991
void Item_cache_int::store(Item *item, longlong val_arg)
5994
null_value= item->null_value;
5995
unsigned_flag= item->unsigned_flag;
5999
String *Item_cache_int::val_str(String *str)
6001
DBUG_ASSERT(fixed == 1);
6002
str->set(value, default_charset());
6007
my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val)
6009
DBUG_ASSERT(fixed == 1);
6010
int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val);
6015
void Item_cache_real::store(Item *item)
6017
value= item->val_result();
6018
null_value= item->null_value;
6022
longlong Item_cache_real::val_int()
6024
DBUG_ASSERT(fixed == 1);
6025
return (longlong) rint(value);
6029
String* Item_cache_real::val_str(String *str)
6031
DBUG_ASSERT(fixed == 1);
6032
str->set_real(value, decimals, default_charset());
6037
my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val)
6039
DBUG_ASSERT(fixed == 1);
6040
double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
6045
void Item_cache_decimal::store(Item *item)
6047
my_decimal *val= item->val_decimal_result(&decimal_value);
6048
if (!(null_value= item->null_value) && val != &decimal_value)
6049
my_decimal2decimal(val, &decimal_value);
6052
double Item_cache_decimal::val_real()
6056
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res);
6060
longlong Item_cache_decimal::val_int()
6064
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res);
6068
String* Item_cache_decimal::val_str(String *str)
6071
my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, FALSE,
6073
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str);
6077
my_decimal *Item_cache_decimal::val_decimal(my_decimal *val)
6080
return &decimal_value;
6084
void Item_cache_str::store(Item *item)
6086
value_buff.set(buffer, sizeof(buffer), item->collation.collation);
6087
value= item->str_result(&value_buff);
6088
if ((null_value= item->null_value))
6090
else if (value != &value_buff)
6093
We copy string value to avoid changing value if 'item' is table field
6094
in queries like following (where t1.c is varchar):
6096
(select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'),
6097
(select c from t1 where a=t2.a)
6100
value_buff.copy(*value);
6105
double Item_cache_str::val_real()
6107
DBUG_ASSERT(fixed == 1);
6111
return my_strntod(value->charset(), (char*) value->ptr(),
6112
value->length(), &end_not_used, &err_not_used);
6117
longlong Item_cache_str::val_int()
6119
DBUG_ASSERT(fixed == 1);
6122
return my_strntoll(value->charset(), value->ptr(),
6123
value->length(), 10, (char**) 0, &err);
6128
my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val)
6130
DBUG_ASSERT(fixed == 1);
6132
string2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
6139
int Item_cache_str::save_in_field(Field *field, bool no_conversions)
6141
int res= Item_cache::save_in_field(field, no_conversions);
6142
return (is_varbinary && field->type() == MYSQL_TYPE_STRING &&
6143
value->length() < field->field_length) ? 1 : res;
6147
bool Item_cache_row::allocate(uint num)
6150
THD *thd= current_thd;
6152
(Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
6156
bool Item_cache_row::setup(Item * item)
6159
if (!values && allocate(item->cols()))
6161
for (uint i= 0; i < item_count; i++)
6163
Item *el= item->element_index(i);
6165
if (!(tmp= values[i]= Item_cache::get_cache(el)))
6173
void Item_cache_row::store(Item * item)
6176
item->bring_value();
6177
for (uint i= 0; i < item_count; i++)
6179
values[i]->store(item->element_index(i));
6180
null_value|= values[i]->null_value;
6185
void Item_cache_row::illegal_method_call(const char *method)
6187
DBUG_ENTER("Item_cache_row::illegal_method_call");
6188
DBUG_PRINT("error", ("!!! %s method was called for row item", method));
6190
my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
6195
bool Item_cache_row::check_cols(uint c)
6197
if (c != item_count)
6199
my_error(ER_OPERAND_COLUMNS, MYF(0), c);
6206
bool Item_cache_row::null_inside()
6208
for (uint i= 0; i < item_count; i++)
6210
if (values[i]->cols() > 1)
6212
if (values[i]->null_inside())
6217
values[i]->update_null_value();
6218
if (values[i]->null_value)
6226
void Item_cache_row::bring_value()
6228
for (uint i= 0; i < item_count; i++)
6229
values[i]->bring_value();
6234
Item_type_holder::Item_type_holder(THD *thd, Item *item)
6235
:Item(thd, item), enum_set_typelib(0), fld_type(get_real_type(item))
6237
DBUG_ASSERT(item->fixed);
6238
maybe_null= item->maybe_null;
6239
collation.set(item->collation);
6240
get_full_info(item);
6241
/* fix variable decimals which always is NOT_FIXED_DEC */
6242
if (Field::result_merge_type(fld_type) == INT_RESULT)
6244
prev_decimal_int_part= item->decimal_int_part();
6249
Return expression type of Item_type_holder.
6252
Item_result (type of internal MySQL expression result)
6255
Item_result Item_type_holder::result_type() const
6257
return Field::result_merge_type(fld_type);
6262
Find real field type of item.
6265
type of field which should be created to store item value
6268
enum_field_types Item_type_holder::get_real_type(Item *item)
6270
switch(item->type())
6275
Item_fields::field_type ask Field_type() but sometimes field return
6276
a different type, like for enum/set, so we need to ask real type.
6278
Field *field= ((Item_field *) item)->field;
6279
enum_field_types type= field->real_type();
6280
if (field->is_created_from_null_item)
6281
return MYSQL_TYPE_NULL;
6282
/* work around about varchar type field detection */
6283
if (type == MYSQL_TYPE_STRING && field->type() == MYSQL_TYPE_VAR_STRING)
6284
return MYSQL_TYPE_VAR_STRING;
6290
Argument of aggregate function sometimes should be asked about field
6293
Item_sum *item_sum= (Item_sum *) item;
6294
if (item_sum->keep_field_type())
6295
return get_real_type(item_sum->args[0]);
6299
if (((Item_func *) item)->functype() == Item_func::GUSERVAR_FUNC)
6302
There are work around of problem with changing variable type on the
6303
fly and variable always report "string" as field type to get
6304
acceptable information for client in send_field, so we make field
6305
type from expression type.
6307
switch (item->result_type()) {
6309
return MYSQL_TYPE_VAR_STRING;
6311
return MYSQL_TYPE_LONGLONG;
6313
return MYSQL_TYPE_DOUBLE;
6314
case DECIMAL_RESULT:
6315
return MYSQL_TYPE_NEWDECIMAL;
6319
return MYSQL_TYPE_VAR_STRING;
6326
return item->field_type();
6330
Find field type which can carry current Item_type_holder type and
6333
@param thd thread handler
6334
@param item given item to join its parameters with this item ones
6337
TRUE error - types are incompatible
6342
bool Item_type_holder::join_types(THD *thd, Item *item)
6344
uint max_length_orig= max_length;
6345
uint decimals_orig= decimals;
6346
DBUG_ENTER("Item_type_holder::join_types");
6347
DBUG_PRINT("info:", ("was type %d len %d, dec %d name %s",
6348
fld_type, max_length, decimals,
6349
(name ? name : "<NULL>")));
6350
DBUG_PRINT("info:", ("in type %d len %d, dec %d",
6351
get_real_type(item),
6352
item->max_length, item->decimals));
6353
fld_type= Field::field_type_merge(fld_type, get_real_type(item));
6355
int item_decimals= item->decimals;
6356
/* fix variable decimals which always is NOT_FIXED_DEC */
6357
if (Field::result_merge_type(fld_type) == INT_RESULT)
6359
decimals= max(decimals, item_decimals);
6361
if (Field::result_merge_type(fld_type) == DECIMAL_RESULT)
6363
decimals= min(max(decimals, item->decimals), DECIMAL_MAX_SCALE);
6364
int precision= min(max(prev_decimal_int_part, item->decimal_int_part())
6365
+ decimals, DECIMAL_MAX_PRECISION);
6366
unsigned_flag&= item->unsigned_flag;
6367
max_length= my_decimal_precision_to_length(precision, decimals,
6371
switch (Field::result_merge_type(fld_type))
6375
const char *old_cs, *old_derivation;
6376
uint32 old_max_chars= max_length / collation.collation->mbmaxlen;
6377
old_cs= collation.collation->name;
6378
old_derivation= collation.derivation_name();
6379
if (collation.aggregate(item->collation, MY_COLL_ALLOW_CONV))
6381
my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
6382
old_cs, old_derivation,
6383
item->collation.collation->name,
6384
item->collation.derivation_name(),
6389
To figure out max_length, we have to take into account possible
6390
expansion of the size of the values because of character set
6393
if (collation.collation != &my_charset_bin)
6395
max_length= max(old_max_chars * collation.collation->mbmaxlen,
6396
display_length(item) /
6397
item->collation.collation->mbmaxlen *
6398
collation.collation->mbmaxlen);
6401
set_if_bigger(max_length, display_length(item));
6406
if (decimals != NOT_FIXED_DEC)
6408
int delta1= max_length_orig - decimals_orig;
6409
int delta2= item->max_length - item->decimals;
6410
max_length= max(delta1, delta2) + decimals;
6411
if (fld_type == MYSQL_TYPE_FLOAT && max_length > FLT_DIG + 2)
6413
max_length= FLT_DIG + 6;
6414
decimals= NOT_FIXED_DEC;
6416
if (fld_type == MYSQL_TYPE_DOUBLE && max_length > DBL_DIG + 2)
6418
max_length= DBL_DIG + 7;
6419
decimals= NOT_FIXED_DEC;
6423
max_length= (fld_type == MYSQL_TYPE_FLOAT) ? FLT_DIG+6 : DBL_DIG+7;
6427
max_length= max(max_length, display_length(item));
6429
maybe_null|= item->maybe_null;
6430
get_full_info(item);
6432
/* Remember decimal integer part to be used in DECIMAL_RESULT handleng */
6433
prev_decimal_int_part= decimal_int_part();
6434
DBUG_PRINT("info", ("become type: %d len: %u dec: %u",
6435
(int) fld_type, max_length, (uint) decimals));
6440
Calculate lenth for merging result for given Item type.
6442
@param item Item for length detection
6448
uint32 Item_type_holder::display_length(Item *item)
6450
if (item->type() == Item::FIELD_ITEM)
6451
return ((Item_field *)item)->max_disp_length();
6453
switch (item->field_type())
6455
case MYSQL_TYPE_DECIMAL:
6456
case MYSQL_TYPE_TIMESTAMP:
6457
case MYSQL_TYPE_DATE:
6458
case MYSQL_TYPE_TIME:
6459
case MYSQL_TYPE_DATETIME:
6460
case MYSQL_TYPE_YEAR:
6461
case MYSQL_TYPE_NEWDATE:
6462
case MYSQL_TYPE_VARCHAR:
6463
case MYSQL_TYPE_BIT:
6464
case MYSQL_TYPE_NEWDECIMAL:
6465
case MYSQL_TYPE_ENUM:
6466
case MYSQL_TYPE_SET:
6467
case MYSQL_TYPE_TINY_BLOB:
6468
case MYSQL_TYPE_MEDIUM_BLOB:
6469
case MYSQL_TYPE_LONG_BLOB:
6470
case MYSQL_TYPE_BLOB:
6471
case MYSQL_TYPE_VAR_STRING:
6472
case MYSQL_TYPE_STRING:
6473
case MYSQL_TYPE_GEOMETRY:
6474
return item->max_length;
6475
case MYSQL_TYPE_TINY:
6477
case MYSQL_TYPE_SHORT:
6479
case MYSQL_TYPE_LONG:
6480
return MY_INT32_NUM_DECIMAL_DIGITS;
6481
case MYSQL_TYPE_FLOAT:
6483
case MYSQL_TYPE_DOUBLE:
6485
case MYSQL_TYPE_NULL:
6487
case MYSQL_TYPE_LONGLONG:
6489
case MYSQL_TYPE_INT24:
6492
DBUG_ASSERT(0); // we should never go there
6499
Make temporary table field according collected information about type
6502
@param table temporary table for which we create fields
6508
Field *Item_type_holder::make_field_by_type(TABLE *table)
6511
The field functions defines a field to be not null if null_ptr is not 0
6513
uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
6517
case MYSQL_TYPE_ENUM:
6518
DBUG_ASSERT(enum_set_typelib);
6519
field= new Field_enum((uchar *) 0, max_length, null_ptr, 0,
6521
get_enum_pack_length(enum_set_typelib->count),
6522
enum_set_typelib, collation.collation);
6526
case MYSQL_TYPE_SET:
6527
DBUG_ASSERT(enum_set_typelib);
6528
field= new Field_set((uchar *) 0, max_length, null_ptr, 0,
6530
get_set_pack_length(enum_set_typelib->count),
6531
enum_set_typelib, collation.collation);
6535
case MYSQL_TYPE_NULL:
6536
return make_string_field(table);
6540
return tmp_table_field_from_field_type(table, 0);
6545
Get full information from Item about enum/set fields to be able to create
6548
@param item Item for information collection
6550
void Item_type_holder::get_full_info(Item *item)
6552
if (fld_type == MYSQL_TYPE_ENUM ||
6553
fld_type == MYSQL_TYPE_SET)
6555
if (item->type() == Item::SUM_FUNC_ITEM &&
6556
(((Item_sum*)item)->sum_func() == Item_sum::MAX_FUNC ||
6557
((Item_sum*)item)->sum_func() == Item_sum::MIN_FUNC))
6558
item = ((Item_sum*)item)->args[0];
6560
We can have enum/set type after merging only if we have one enum|set
6561
field (or MIN|MAX(enum|set field)) and number of NULL fields
6563
DBUG_ASSERT((enum_set_typelib &&
6564
get_real_type(item) == MYSQL_TYPE_NULL) ||
6565
(!enum_set_typelib &&
6566
item->type() == Item::FIELD_ITEM &&
6567
(get_real_type(item) == MYSQL_TYPE_ENUM ||
6568
get_real_type(item) == MYSQL_TYPE_SET) &&
6569
((Field_enum*)((Item_field *) item)->field)->typelib));
6570
if (!enum_set_typelib)
6572
enum_set_typelib= ((Field_enum*)((Item_field *) item)->field)->typelib;
6578
double Item_type_holder::val_real()
6580
DBUG_ASSERT(0); // should never be called
6585
longlong Item_type_holder::val_int()
6587
DBUG_ASSERT(0); // should never be called
6591
my_decimal *Item_type_holder::val_decimal(my_decimal *)
6593
DBUG_ASSERT(0); // should never be called
6597
String *Item_type_holder::val_str(String*)
6599
DBUG_ASSERT(0); // should never be called
6603
void Item_result_field::cleanup()
6605
DBUG_ENTER("Item_result_field::cleanup()");
6612
Dummy error processor used by default by Name_resolution_context.
6618
void dummy_error_processor(THD *thd, void *data)
6622
Wrapper of hide_view_error call for Name_resolution_context error
6626
hide view underlying tables details in error messages
6629
/*****************************************************************************
6630
** Instantiate templates
6631
*****************************************************************************/
6633
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
6634
template class List<Item>;
6635
template class List_iterator<Item>;
6636
template class List_iterator_fast<Item>;
6637
template class List_iterator_fast<Item_field>;
6638
template class List<List_item>;