1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
4
* Copyright (C) 2008-2009 Sun Microsystems
6
* This program is free software; you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation; version 2 of the License.
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
* GNU General Public License for more details.
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21
#include "drizzled/sql_select.h"
22
#include "drizzled/error.h"
23
#include "drizzled/show.h"
24
#include "drizzled/item/cmpfunc.h"
25
#include "drizzled/item/cache_row.h"
26
#include "drizzled/item/type_holder.h"
27
#include "drizzled/item/sum.h"
28
#include "drizzled/item/copy_string.h"
29
#include "drizzled/function/str/conv_charset.h"
30
#include "drizzled/sql_base.h"
31
#include "drizzled/util/convert.h"
32
#include "drizzled/plugin/client.h"
33
#include "drizzled/time_functions.h"
35
#include "drizzled/field/str.h"
36
#include "drizzled/field/num.h"
37
#include "drizzled/field/blob.h"
38
#include "drizzled/field/enum.h"
39
#include "drizzled/field/null.h"
40
#include "drizzled/field/date.h"
41
#include "drizzled/field/decimal.h"
42
#include "drizzled/field/real.h"
43
#include "drizzled/field/double.h"
44
#include "drizzled/field/long.h"
45
#include "drizzled/field/int64_t.h"
46
#include "drizzled/field/num.h"
47
#include "drizzled/field/timestamp.h"
48
#include "drizzled/field/datetime.h"
49
#include "drizzled/field/varstring.h"
50
#include "drizzled/internal/m_string.h"
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"
61
26
const String my_null_string("NULL", 4, default_charset_info);
63
bool Item::is_expensive_processor(unsigned char *)
68
void Item::fix_after_pullout(Select_Lex *, Item **)
71
Field *Item::tmp_table_field(Table *)
76
const char *Item::full_name(void) const
78
return name ? name : "???";
81
int64_t Item::val_int_endpoint(bool, bool *)
87
/** @todo Make this functions class dependent */
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
88
176
bool Item::val_bool()
178
switch(result_type()) {
180
return val_int() != 0;
93
return val_int() != 0;
96
my_decimal decimal_value;
97
my_decimal *val= val_decimal(&decimal_value);
99
return !my_decimal_is_zero(val);
104
return val_real() != 0.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)
112
200
String *Item::val_string_from_real(String *str)
114
202
double nr= val_real();
118
str->set_real(nr, decimals, &my_charset_bin);
204
return 0; /* purecov: inspected */
205
str->set_real(nr,decimals, &my_charset_bin);
122
210
String *Item::val_string_from_int(String *str)
124
int64_t nr= val_int();
212
longlong nr= val_int();
128
215
str->set_int(nr, unsigned_flag, &my_charset_bin);
132
220
String *Item::val_string_from_decimal(String *str)
134
222
my_decimal dec_buf, *dec= val_decimal(&dec_buf);
138
my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, false, &dec_buf);
225
my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
139
226
my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
143
231
my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
145
233
double nr= val_real();
149
236
double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
150
237
return (decimal_value);
153
241
my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
155
int64_t nr= val_int();
243
longlong nr= val_int();
159
246
int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
160
247
return decimal_value;
163
251
my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
167
255
if (!(res= val_str(&str_value)))
256
return 0; // NULL or EOM
170
258
end_ptr= (char*) res->ptr()+ res->length();
171
259
if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
260
res->ptr(), res->length(), res->charset(),
175
261
decimal_value) & E_DEC_BAD_NUM)
177
push_warning_printf(current_session,
178
DRIZZLE_ERROR::WARN_LEVEL_WARN,
263
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
179
264
ER_TRUNCATED_WRONG_VALUE,
180
265
ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
181
266
str_value.c_ptr());
747
1046
Item_ref to allow fields from view being stored in tmp table.
749
1048
Item_aggregate_ref *item_ref;
750
uint32_t el= fields.elements;
1049
uint el= fields.elements;
751
1050
Item *real_itm= real_item();
753
1052
ref_pointer_array[el]= real_itm;
754
if (!(item_ref= new Item_aggregate_ref(&session->lex->current_select->context,
1053
if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context,
755
1054
ref_pointer_array + el, 0, name)))
756
return; /* fatal_error is set */
1055
return; // fatal_error is set
757
1056
if (type() == SUM_FUNC_ITEM)
758
item_ref->depended_from= ((Item_sum *) this)->depended_from();
1057
item_ref->depended_from= ((Item_sum *) this)->depended_from();
759
1058
fields.push_front(real_itm);
760
session->change_item_tree(ref, item_ref);
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);
765
2832
Functions to convert item to field (for send_fields)
767
bool Item::fix_fields(Session *, Item **)
769
/* We do not check fields which are fixed during construction */
770
assert(! fixed || basic_const_item());
775
void mark_as_dependent(Session *session, Select_Lex *last, Select_Lex *current,
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,
776
2909
Item_ident *resolved_item,
777
2910
Item_ident *mark_item)
981
3180
if (select_ref != not_found_item && !ambiguous_fields)
983
assert(*select_ref != 0);
3182
DBUG_ASSERT(*select_ref != 0);
984
3183
if (!select->ref_pointer_array[counter])
986
3185
my_error(ER_ILLEGAL_REFERENCE, MYF(0),
987
3186
ref->name, "forward reference in item list");
990
assert((*select_ref)->fixed);
3189
DBUG_ASSERT((*select_ref)->fixed);
991
3190
return (select->ref_pointer_array + counter);
993
3192
if (group_by_ref)
994
3193
return group_by_ref;
996
3195
return NULL; /* So there is no compiler warning. */
999
3198
return (Item**) not_found_item;
1002
void Item::init_make_field(SendField *tmp_field,
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,
1003
3932
enum enum_field_types field_type_arg)
1005
3934
char *empty_name= (char*) "";
1006
tmp_field->db_name= empty_name;
1007
tmp_field->org_table_name= empty_name;
1008
tmp_field->org_col_name= empty_name;
1009
tmp_field->table_name= empty_name;
1010
tmp_field->col_name= name;
1011
tmp_field->charsetnr= collation.collation->number;
1012
tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
1013
(my_binary_compare(collation.collation) ?
1015
tmp_field->type= field_type_arg;
1016
tmp_field->length= max_length;
1017
tmp_field->decimals= decimals;
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;
1020
void Item::make_field(SendField *tmp_field)
3951
void Item::make_field(Send_field *tmp_field)
1022
3953
init_make_field(tmp_field, field_type());
1025
3957
enum_field_types Item::string_field_type() const
1027
enum_field_types f_type= DRIZZLE_TYPE_VARCHAR;
1028
if (max_length >= 65536)
1029
f_type= DRIZZLE_TYPE_BLOB;
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());
1033
3974
enum_field_types Item::field_type() const
1035
3976
switch (result_type()) {
1037
return string_field_type();
1039
return DRIZZLE_TYPE_LONGLONG;
1040
case DECIMAL_RESULT:
1041
return DRIZZLE_TYPE_DECIMAL;
1043
return DRIZZLE_TYPE_DOUBLE;
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;
1044
3981
case ROW_RESULT:
1047
return DRIZZLE_TYPE_VARCHAR;
3984
return MYSQL_TYPE_VARCHAR;
1051
3989
bool Item::is_datetime()
1053
3991
switch (field_type())
1055
case DRIZZLE_TYPE_DATE:
1056
case DRIZZLE_TYPE_DATETIME:
1057
case DRIZZLE_TYPE_TIMESTAMP:
3993
case MYSQL_TYPE_DATE:
3994
case MYSQL_TYPE_DATETIME:
3995
case MYSQL_TYPE_TIMESTAMP:
1065
4004
String *Item::check_well_formed_result(String *str, bool send_error)
1067
4006
/* Check whether we got a well-formed string */
1068
const CHARSET_INFO * const cs= str->charset();
4007
CHARSET_INFO *cs= str->charset();
1069
4008
int well_formed_error;
1070
uint32_t wlen= cs->cset->well_formed_len(cs,
4009
uint wlen= cs->cset->well_formed_len(cs,
1071
4010
str->ptr(), str->ptr() + str->length(),
1072
4011
str->length(), &well_formed_error);
1073
4012
if (wlen < str->length())
1075
Session *session= current_session;
4014
THD *thd= current_thd;
1076
4015
char hexbuf[7];
1077
enum DRIZZLE_ERROR::enum_warning_level level;
1078
uint32_t diff= str->length() - wlen;
1079
set_if_smaller(diff, 3U);
1080
(void) drizzled_string_to_hex(hexbuf, str->ptr() + wlen, diff);
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);
1081
4020
if (send_error)
1083
4022
my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
1084
4023
cs->csname, hexbuf);
1088
level= DRIZZLE_ERROR::WARN_LEVEL_ERROR;
4027
level= MYSQL_ERROR::WARN_LEVEL_ERROR;
1092
push_warning_printf(session, level, ER_INVALID_CHARACTER_STRING,
4031
push_warning_printf(thd, level, ER_INVALID_CHARACTER_STRING,
1093
4032
ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
1098
bool Item::eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO * const cs)
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)
1100
const CHARSET_INFO *save_cs= 0;
1101
const CHARSET_INFO *save_item_cs= 0;
4060
CHARSET_INFO *save_cs= 0;
4061
CHARSET_INFO *save_item_cs= 0;
1102
4062
if (collation.collation != cs)
1104
4064
save_cs= collation.collation;
1265
Check if an item is a constant one and can be cached.
1267
@param arg [out] TRUE <=> Cache this item.
1269
@return TRUE Go deeper in item tree.
1270
@return FALSE Don't go deeper in item tree.
1273
bool Item::cache_const_expr_analyzer(unsigned char **arg)
1275
bool *cache_flag= (bool*)*arg;
1278
Item *item= real_item();
1280
Cache constant items unless it's a basic constant, constant field or
1281
a subselect (they use their own cache).
1284
!(item->basic_const_item() || item->type() == Item::FIELD_ITEM ||
1285
item->type() == SUBSELECT_ITEM ||
1287
Do not cache GET_USER_VAR() function as its const_item() may
1288
return TRUE for the current thread but it still may change
1289
during the execution.
1291
(item->type() == Item::FUNC_ITEM &&
1292
((Item_func*)item)->functype() == Item_func::GUSERVAR_FUNC)))
1300
Cache item if needed.
1302
@param arg TRUE <=> Cache this item.
1304
@return cache if cache needed.
1305
@return this otherwise.
1308
Item* Item::cache_const_expr_transformer(unsigned char *arg)
1312
*((bool*)arg)= false;
1313
Item_cache *cache= Item_cache::get_cache(this);
1323
bool Item::send(plugin::Client *client, String *buffer)
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)
1325
4720
bool result= false;
1326
4721
enum_field_types f_type;
1328
4723
switch ((f_type=field_type())) {
1330
case DRIZZLE_TYPE_NULL:
1331
case DRIZZLE_TYPE_ENUM:
1332
case DRIZZLE_TYPE_BLOB:
1333
case DRIZZLE_TYPE_VARCHAR:
1334
case DRIZZLE_TYPE_DECIMAL:
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:
1337
4740
if ((res=val_str(buffer)))
1338
result= client->store(res->ptr(),res->length());
1341
case DRIZZLE_TYPE_LONG:
1346
result= client->store((int32_t)nr);
1349
case DRIZZLE_TYPE_LONGLONG:
1356
result= client->store((uint64_t)nr);
1358
result= client->store((int64_t)nr);
1362
case DRIZZLE_TYPE_DOUBLE:
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:
1364
4788
double nr= val_real();
1365
4789
if (!null_value)
1366
result= client->store(nr, decimals, buffer);
4790
result= protocol->store(nr, decimals, buffer);
1369
case DRIZZLE_TYPE_DATETIME:
1370
case DRIZZLE_TYPE_TIMESTAMP:
4793
case MYSQL_TYPE_DATETIME:
4794
case MYSQL_TYPE_DATE:
4795
case MYSQL_TYPE_TIMESTAMP:
1373
4798
get_date(&tm, TIME_FUZZY_DATE);
1374
4799
if (!null_value)
1375
result= client->store(&tm);
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);
1379
4817
if (null_value)
1380
result= client->store();
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);
1384
5801
Item_result item_cmp_type(Item_result a,Item_result b)
1386
5803
if (a == STRING_RESULT && b == STRING_RESULT)
1522
5948
return result == field->val_real();
1525
void dummy_error_processor(Session *, void *)
1529
Create field for temporary table using type of given item.
1531
@param session Thread handler
1532
@param item Item to create a field for
1533
@param table Temporary table
1534
@param copy_func If set and item is a function, store copy of
1536
@param modify_item 1 if item->result_field should point to new
1537
item. This is relevent for how fill_record()
1539
If modify_item is 1 then fill_record() will
1540
update the record in the original table.
1541
If modify_item is 0 then fill_record() will
1542
update the temporary table
1543
@param convert_blob_length If >0 create a varstring(convert_blob_length)
1544
field instead of blob.
1551
static Field *create_tmp_field_from_item(Session *,
1552
Item *item, Table *table,
1553
Item ***copy_func, bool modify_item,
1554
uint32_t convert_blob_length)
5951
Item_cache* Item_cache::get_cache(const Item *item)
1556
bool maybe_null= item->maybe_null;
1559
5953
switch (item->result_type()) {
1561
new_field= new Field_double(item->max_length, maybe_null,
1562
item->name, item->decimals, true);
1564
5954
case INT_RESULT:
1566
Select an integer type with the minimal fit precision.
1567
MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
1568
Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into
1569
Field_long : make them Field_int64_t.
1571
if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
1572
new_field=new Field_int64_t(item->max_length, maybe_null,
1573
item->name, item->unsigned_flag);
1575
new_field=new Field_long(item->max_length, maybe_null,
1576
item->name, item->unsigned_flag);
1579
assert(item->collation.collation);
1581
enum enum_field_types type;
1583
DATE/TIME fields have STRING_RESULT result type.
1584
To preserve type they needed to be handled separately.
1586
if ((type= item->field_type()) == DRIZZLE_TYPE_DATETIME ||
1587
type == DRIZZLE_TYPE_DATE ||
1588
type == DRIZZLE_TYPE_TIMESTAMP)
1589
new_field= item->tmp_table_field_from_field_type(table, 1);
1591
Make sure that the blob fits into a Field_varstring which has
1594
else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
1595
convert_blob_length <= Field_varstring::MAX_SIZE &&
1596
convert_blob_length)
1597
new_field= new Field_varstring(convert_blob_length, maybe_null,
1598
item->name, table->s,
1599
item->collation.collation);
1601
new_field= item->make_string_field(table);
1602
new_field->set_derivation(item->collation.derivation);
5955
return new Item_cache_int();
5957
return new Item_cache_real();
1604
5958
case DECIMAL_RESULT:
1606
uint8_t dec= item->decimals;
1607
uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
1608
uint32_t len= item->max_length;
1611
Trying to put too many digits overall in a DECIMAL(prec,dec)
1612
will always throw a warning. We must limit dec to
1613
DECIMAL_MAX_SCALE however to prevent an assert() later.
1618
signed int overflow;
1620
dec= min(dec, (uint8_t)DECIMAL_MAX_SCALE);
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)
1623
If the value still overflows the field with the corrected dec,
1624
we'll throw out decimals rather than integers. This is still
1625
bad and of course throws a truncation warning.
1626
+1: for decimal point
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.
1629
overflow= my_decimal_precision_to_length(intg + dec, dec,
1630
item->unsigned_flag) - len;
1633
dec= max(0, dec - overflow); // too long, discard fract
1635
len-= item->decimals - dec; // corrected value fits
1638
new_field= new Field_decimal(len,
1642
item->unsigned_flag);
1647
// This case should never be choosen
1653
new_field->init(table);
1655
if (copy_func && item->is_result_field())
1656
*((*copy_func)++) = item; // Save for copy_funcs
1658
item->set_result_field(new_field);
1659
if (item->type() == Item::NULL_ITEM)
1660
new_field->is_created_from_null_item= true;
1664
Field *create_tmp_field(Session *session,
1670
Field **default_field,
1673
bool make_copy_field,
1674
uint32_t convert_blob_length)
1677
Item::Type orig_type= type;
1680
if (type != Item::FIELD_ITEM &&
1681
item->real_item()->type() == Item::FIELD_ITEM)
1684
item= item->real_item();
1685
type= Item::FIELD_ITEM;
1689
case Item::SUM_FUNC_ITEM:
1691
Item_sum *item_sum=(Item_sum*) item;
1692
result= item_sum->create_tmp_field(group, table, convert_blob_length);
1694
my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
1697
case Item::FIELD_ITEM:
1698
case Item::DEFAULT_VALUE_ITEM:
1700
Item_field *field= (Item_field*) item;
1701
bool orig_modify= modify_item;
1702
if (orig_type == Item::REF_ITEM)
1705
If item have to be able to store NULLs but underlaid field can't do it,
1706
create_tmp_field_from_field() can't be used for tmp field creation.
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
1708
if (field->maybe_null && !field->field->maybe_null())
1710
result= create_tmp_field_from_item(session, item, table, NULL,
1711
modify_item, convert_blob_length);
1712
*from_field= field->field;
1713
if (result && modify_item)
1714
field->result_field= result;
1717
result= create_tmp_field_from_field(session, (*from_field= field->field),
1718
orig_item ? orig_item->name :
1721
modify_item ? field :
1723
convert_blob_length);
1724
if (orig_type == Item::REF_ITEM && orig_modify)
1725
((Item_ref*)orig_item)->set_result_field(result);
1726
if (field->field->eq_def(result))
1727
*default_field= field->field;
1731
case Item::FUNC_ITEM:
1733
case Item::COND_ITEM:
1734
case Item::FIELD_AVG_ITEM:
1735
case Item::FIELD_STD_ITEM:
1736
case Item::SUBSELECT_ITEM:
1737
/* The following can only happen with 'CREATE TABLE ... SELECT' */
1738
case Item::PROC_ITEM:
1739
case Item::INT_ITEM:
1740
case Item::REAL_ITEM:
1741
case Item::DECIMAL_ITEM:
1742
case Item::STRING_ITEM:
1743
case Item::REF_ITEM:
1744
case Item::NULL_ITEM:
1745
case Item::VARBIN_ITEM:
1746
if (make_copy_field)
1748
assert(((Item_result_field*)item)->result_field);
1749
*from_field= ((Item_result_field*)item)->result_field;
1751
return create_tmp_field_from_item(session, item, table,
1752
(make_copy_field ? 0 : copy_func),
1753
modify_item, convert_blob_length);
1754
case Item::TYPE_HOLDER:
1755
result= ((Item_type_holder *)item)->make_field_by_type(table);
1756
result->set_derivation(item->collation.derivation);
1758
default: // Dosen't have to be stored
1763
} /* namespace drizzled */
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>;