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/int32.h"
45
#include "drizzled/field/int64.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"
23
#include "sql_select.h"
62
25
const String my_null_string("NULL", 4, default_charset_info);
64
bool Item::is_expensive_processor(unsigned char *)
69
void Item::fix_after_pullout(Select_Lex *, Item **)
72
Field *Item::tmp_table_field(Table *)
77
const char *Item::full_name(void) const
79
return name ? name : "???";
82
int64_t Item::val_int_endpoint(bool, bool *)
88
/** @todo Make this functions class dependent */
27
/****************************************************************************/
29
/* Hybrid_type_traits {_real} */
31
void Hybrid_type_traits::fix_length_and_dec(Item *item, Item *arg) const
33
item->decimals= NOT_FIXED_DEC;
34
item->max_length= item->float_length(arg->decimals);
37
static const Hybrid_type_traits real_traits_instance;
39
const Hybrid_type_traits *Hybrid_type_traits::instance()
41
return &real_traits_instance;
46
Hybrid_type_traits::val_decimal(Hybrid_type *val,
47
my_decimal *to __attribute__((__unused__))) 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,
151
Item *arg __attribute__((__unused__))) const
154
item->max_length= MY_INT64_NUM_DECIMAL_DIGITS;
155
item->unsigned_flag= 0;
158
/*****************************************************************************
160
*****************************************************************************/
163
Init all special items.
174
Make this functions class dependent
89
177
bool Item::val_bool()
179
switch(result_type()) {
181
return val_int() != 0;
94
return val_int() != 0;
98
my_decimal decimal_value;
99
my_decimal *val= val_decimal(&decimal_value);
101
return !my_decimal_is_zero(val);
107
return val_real() != 0.0;
184
my_decimal decimal_value;
185
my_decimal *val= val_decimal(&decimal_value);
187
return !my_decimal_is_zero(val);
192
return val_real() != 0.0;
196
return 0; // Wrong (but safe)
118
201
String *Item::val_string_from_real(String *str)
120
203
double nr= val_real();
124
str->set_real(nr, decimals, &my_charset_bin);
205
return 0; /* purecov: inspected */
206
str->set_real(nr,decimals, &my_charset_bin);
128
211
String *Item::val_string_from_int(String *str)
130
int64_t nr= val_int();
213
longlong nr= val_int();
134
216
str->set_int(nr, unsigned_flag, &my_charset_bin);
138
221
String *Item::val_string_from_decimal(String *str)
140
223
my_decimal dec_buf, *dec= val_decimal(&dec_buf);
144
226
my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, false, &dec_buf);
145
227
my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
149
232
my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
151
234
double nr= val_real();
155
237
double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
156
238
return (decimal_value);
159
242
my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
161
int64_t nr= val_int();
244
longlong nr= val_int();
165
247
int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
166
248
return decimal_value;
169
252
my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
173
256
if (!(res= val_str(&str_value)))
257
return 0; // NULL or EOM
176
259
end_ptr= (char*) res->ptr()+ res->length();
177
260
if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
261
res->ptr(), res->length(), res->charset(),
181
262
decimal_value) & E_DEC_BAD_NUM)
183
push_warning_printf(current_session,
184
DRIZZLE_ERROR::WARN_LEVEL_WARN,
264
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
185
265
ER_TRUNCATED_WRONG_VALUE,
186
266
ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
187
267
str_value.c_ptr());
753
1042
Item_ref to allow fields from view being stored in tmp table.
755
1044
Item_aggregate_ref *item_ref;
756
uint32_t el= fields.elements;
1045
uint el= fields.elements;
757
1046
Item *real_itm= real_item();
759
1048
ref_pointer_array[el]= real_itm;
760
if (!(item_ref= new Item_aggregate_ref(&session->lex->current_select->context,
1049
if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context,
761
1050
ref_pointer_array + el, 0, name)))
762
return; /* fatal_error is set */
1051
return; // fatal_error is set
763
1052
if (type() == SUM_FUNC_ITEM)
764
item_ref->depended_from= ((Item_sum *) this)->depended_from();
1053
item_ref->depended_from= ((Item_sum *) this)->depended_from();
765
1054
fields.push_front(real_itm);
766
session->change_item_tree(ref, item_ref);
1055
thd->change_item_tree(ref, item_ref);
1061
left_is_superset(DTCollation *left, DTCollation *right)
1063
/* Allow convert to Unicode */
1064
if (left->collation->state & MY_CS_UNICODE &&
1065
(left->derivation < right->derivation ||
1066
(left->derivation == right->derivation &&
1067
!(right->collation->state & MY_CS_UNICODE))))
1069
/* Allow convert from ASCII */
1070
if (right->repertoire == MY_REPERTOIRE_ASCII &&
1071
(left->derivation < right->derivation ||
1072
(left->derivation == right->derivation &&
1073
!(left->repertoire == MY_REPERTOIRE_ASCII))))
1075
/* Disallow conversion otherwise */
1080
Aggregate two collations together taking
1081
into account their coercibility (aka derivation):.
1083
0 == DERIVATION_EXPLICIT - an explicitly written COLLATE clause @n
1084
1 == DERIVATION_NONE - a mix of two different collations @n
1085
2 == DERIVATION_IMPLICIT - a column @n
1086
3 == DERIVATION_COERCIBLE - a string constant.
1088
The most important rules are:
1089
-# If collations are the same:
1090
chose this collation, and the strongest derivation.
1091
-# If collations are different:
1092
- Character sets may differ, but only if conversion without
1093
data loss is possible. The caller provides flags whether
1094
character set conversion attempts should be done. If no
1095
flags are substituted, then the character sets must be the same.
1096
Currently processed flags are:
1097
MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset
1098
MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
1099
- two EXPLICIT collations produce an error, e.g. this is wrong:
1100
CONCAT(expr1 collate latin1_swedish_ci, expr2 collate latin1_german_ci)
1101
- the side with smaller derivation value wins,
1102
i.e. a column is stronger than a string constant,
1103
an explicit COLLATE clause is stronger than a column.
1104
- if derivations are the same, we have DERIVATION_NONE,
1105
we'll wait for an explicit COLLATE clause which possibly can
1106
come from another argument later: for example, this is valid,
1107
but we don't know yet when collecting the first two arguments:
1109
CONCAT(latin1_swedish_ci_column,
1110
latin1_german1_ci_column,
1111
expr COLLATE latin1_german2_ci)
1115
bool DTCollation::aggregate(DTCollation &dt, uint flags)
1117
if (!my_charset_same(collation, dt.collation))
1120
We do allow to use binary strings (like BLOBS)
1121
together with character strings.
1122
Binaries have more precedence than a character
1123
string of the same derivation.
1125
if (collation == &my_charset_bin)
1127
if (derivation <= dt.derivation)
1134
else if (dt.collation == &my_charset_bin)
1136
if (dt.derivation <= derivation)
1145
else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
1146
left_is_superset(this, &dt))
1150
else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
1151
left_is_superset(&dt, this))
1155
else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
1156
derivation < dt.derivation &&
1157
dt.derivation >= DERIVATION_SYSCONST)
1161
else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
1162
dt.derivation < derivation &&
1163
derivation >= DERIVATION_SYSCONST)
1169
// Cannot apply conversion
1170
set(0, DERIVATION_NONE, 0);
1174
else if (derivation < dt.derivation)
1178
else if (dt.derivation < derivation)
1184
if (collation == dt.collation)
1190
if (derivation == DERIVATION_EXPLICIT)
1192
set(0, DERIVATION_NONE, 0);
1195
if (collation->state & MY_CS_BINSORT)
1197
if (dt.collation->state & MY_CS_BINSORT)
1202
CHARSET_INFO *bin= get_charset_by_csname(collation->csname,
1203
MY_CS_BINSORT,MYF(0));
1204
set(bin, DERIVATION_NONE);
1207
repertoire|= dt.repertoire;
1211
/******************************/
1213
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname)
1215
my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
1216
c1.collation->name,c1.derivation_name(),
1217
c2.collation->name,c2.derivation_name(),
1223
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, DTCollation &c3,
1226
my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0),
1227
c1.collation->name,c1.derivation_name(),
1228
c2.collation->name,c2.derivation_name(),
1229
c3.collation->name,c3.derivation_name(),
1235
void my_coll_agg_error(Item** args, uint count, const char *fname,
1239
my_coll_agg_error(args[0]->collation, args[item_sep]->collation, fname);
1240
else if (count == 3)
1241
my_coll_agg_error(args[0]->collation, args[item_sep]->collation,
1242
args[2*item_sep]->collation, fname);
1244
my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname);
1248
bool agg_item_collations(DTCollation &c, const char *fname,
1249
Item **av, uint count, uint flags, int item_sep)
1253
c.set(av[0]->collation);
1254
for (i= 1, arg= &av[item_sep]; i < count; i++, arg++)
1256
if (c.aggregate((*arg)->collation, flags))
1258
my_coll_agg_error(av, count, fname, item_sep);
1262
if ((flags & MY_COLL_DISALLOW_NONE) &&
1263
c.derivation == DERIVATION_NONE)
1265
my_coll_agg_error(av, count, fname, item_sep);
1272
bool agg_item_collations_for_comparison(DTCollation &c, const char *fname,
1273
Item **av, uint count, uint flags)
1275
return (agg_item_collations(c, fname, av, count,
1276
flags | MY_COLL_DISALLOW_NONE, 1));
1281
Collect arguments' character sets together.
1283
We allow to apply automatic character set conversion in some cases.
1284
The conditions when conversion is possible are:
1285
- arguments A and B have different charsets
1286
- A wins according to coercibility rules
1287
(i.e. a column is stronger than a string constant,
1288
an explicit COLLATE clause is stronger than a column)
1289
- character set of A is either superset for character set of B,
1290
or B is a string constant which can be converted into the
1291
character set of A without data loss.
1293
If all of the above is true, then it's possible to convert
1294
B into the character set of A, and then compare according
1295
to the collation of A.
1297
For functions with more than two arguments:
1299
collect(A,B,C) ::= collect(collect(A,B),C)
1301
Since this function calls THD::change_item_tree() on the passed Item **
1302
pointers, it is necessary to pass the original Item **'s, not copies.
1303
Otherwise their values will not be properly restored (see BUG#20769).
1304
If the items are not consecutive (eg. args[2] and args[5]), use the
1305
item_sep argument, ie.
1307
agg_item_charsets(coll, fname, &args[2], 2, flags, 3)
1311
bool agg_item_charsets(DTCollation &coll, const char *fname,
1312
Item **args, uint nargs, uint flags, int item_sep)
1314
Item **arg, *safe_args[2];
1316
memset(safe_args, 0, sizeof(safe_args));
1318
if (agg_item_collations(coll, fname, args, nargs, flags, item_sep))
1322
For better error reporting: save the first and the second argument.
1323
We need this only if the the number of args is 3 or 2:
1324
- for a longer argument list, "Illegal mix of collations"
1325
doesn't display each argument's characteristics.
1326
- if nargs is 1, then this error cannot happen.
1328
if (nargs >=2 && nargs <= 3)
1330
safe_args[0]= args[0];
1331
safe_args[1]= args[item_sep];
1334
THD *thd= current_thd;
1335
Query_arena *arena, backup;
1339
In case we're in statement prepare, create conversion item
1340
in its memory: it will be reused on each execute.
1344
for (i= 0, arg= args; i < nargs; i++, arg+= item_sep)
1347
uint32 dummy_offset;
1348
if (!String::needs_conversion(0, (*arg)->collation.collation,
1353
if (!(conv= (*arg)->safe_charset_converter(coll.collation)) &&
1354
((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII))
1355
conv= new Item_func_conv_charset(*arg, coll.collation, 1);
1359
if (nargs >=2 && nargs <= 3)
1361
/* restore the original arguments for better error message */
1362
args[0]= safe_args[0];
1363
args[item_sep]= safe_args[1];
1365
my_coll_agg_error(args, nargs, fname, item_sep);
1367
break; // we cannot return here, we need to restore "arena".
1369
if ((*arg)->type() == Item::FIELD_ITEM)
1370
((Item_field *)(*arg))->no_const_subst= 1;
1372
If in statement prepare, then we create a converter for two
1373
constant items, do it once and then reuse it.
1374
If we're in execution of a prepared statement, arena is NULL,
1375
and the conv was created in runtime memory. This can be
1376
the case only if the argument is a parameter marker ('?'),
1377
because for all true constants the charset converter has already
1378
been created in prepare. In this case register the change for
1381
thd->change_item_tree(arg, conv);
1383
We do not check conv->fixed, because Item_func_conv_charset which can
1384
be return by safe_charset_converter can't be fixed at creation
1386
conv->fix_fields(thd, arg);
1389
thd->restore_active_arena(arena, &backup);
1394
void Item_ident_for_show::make_field(Send_field *tmp_field)
1396
tmp_field->table_name= tmp_field->org_table_name= table_name;
1397
tmp_field->db_name= db_name;
1398
tmp_field->col_name= tmp_field->org_col_name= field->field_name;
1399
tmp_field->charsetnr= field->charset()->number;
1400
tmp_field->length=field->field_length;
1401
tmp_field->type=field->type();
1402
tmp_field->flags= field->table->maybe_null ?
1403
(field->flags & ~NOT_NULL_FLAG) : field->flags;
1404
tmp_field->decimals= field->decimals();
1407
/**********************************************/
1409
Item_field::Item_field(Field *f)
1410
:Item_ident(0, NullS, *f->table_name, f->field_name),
1411
item_equal(0), no_const_subst(0),
1412
have_privileges(0), any_privileges(0)
1416
field_name and table_name should not point to garbage
1417
if this item is to be reused
1419
orig_table_name= orig_field_name= "";
1424
Constructor used inside setup_wild().
1426
Ensures that field, table, and database names will live as long as
1427
Item_field (this is important in prepared statements).
1430
Item_field::Item_field(THD *thd __attribute__((__unused__)),
1431
Name_resolution_context *context_arg,
1433
:Item_ident(context_arg, f->table->s->db.str, *f->table_name, f->field_name),
1434
item_equal(0), no_const_subst(0),
1435
have_privileges(0), any_privileges(0)
1441
Item_field::Item_field(Name_resolution_context *context_arg,
1442
const char *db_arg,const char *table_name_arg,
1443
const char *field_name_arg)
1444
:Item_ident(context_arg, db_arg,table_name_arg,field_name_arg),
1445
field(0), result_field(0), item_equal(0), no_const_subst(0),
1446
have_privileges(0), any_privileges(0)
1448
SELECT_LEX *select= current_thd->lex->current_select;
1449
collation.set(DERIVATION_IMPLICIT);
1450
if (select && select->parsing_place != IN_HAVING)
1451
select->select_n_where_fields++;
1455
Constructor need to process subselect with temporary tables (see Item)
1458
Item_field::Item_field(THD *thd, Item_field *item)
1459
:Item_ident(thd, item),
1461
result_field(item->result_field),
1462
item_equal(item->item_equal),
1463
no_const_subst(item->no_const_subst),
1464
have_privileges(item->have_privileges),
1465
any_privileges(item->any_privileges)
1467
collation.set(DERIVATION_IMPLICIT);
1470
void Item_field::set_field(Field *field_par)
1472
field=result_field=field_par; // for easy coding with fields
1473
maybe_null=field->maybe_null();
1474
decimals= field->decimals();
1475
max_length= field_par->max_display_length();
1476
table_name= *field_par->table_name;
1477
field_name= field_par->field_name;
1478
db_name= field_par->table->s->db.str;
1479
alias_name_used= field_par->table->alias_name_used;
1480
unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
1481
collation.set(field_par->charset(), field_par->derivation());
1483
if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
1489
Reset this item to point to a field from the new temporary table.
1490
This is used when we create a new temporary table for each execution
1491
of prepared statement.
1494
void Item_field::reset_field(Field *f)
1497
/* 'name' is pointing at field->field_name of old field */
1498
name= (char*) f->field_name;
1501
const char *Item_ident::full_name() const
1504
if (!table_name || !field_name)
1505
return field_name ? field_name : name ? name : "tmp_field";
1506
if (db_name && db_name[0])
1508
tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
1509
(uint) strlen(field_name)+3);
1510
strxmov(tmp,db_name,".",table_name,".",field_name,NullS);
1516
tmp= (char*) sql_alloc((uint) strlen(table_name) +
1517
(uint) strlen(field_name) + 2);
1518
strxmov(tmp, table_name, ".", field_name, NullS);
1521
tmp= (char*) field_name;
1526
void Item_ident::print(String *str,
1527
enum_query_type query_type __attribute__((__unused__)))
1529
THD *thd= current_thd;
1530
char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
1531
const char *d_name= db_name, *t_name= table_name;
1532
if (lower_case_table_names== 1 ||
1533
(lower_case_table_names == 2 && !alias_name_used))
1535
if (table_name && table_name[0])
1537
strmov(t_name_buff, table_name);
1538
my_casedn_str(files_charset_info, t_name_buff);
1539
t_name= t_name_buff;
1541
if (db_name && db_name[0])
1543
strmov(d_name_buff, db_name);
1544
my_casedn_str(files_charset_info, d_name_buff);
1545
d_name= d_name_buff;
1549
if (!table_name || !field_name || !field_name[0])
1551
const char *nm= (field_name && field_name[0]) ?
1552
field_name : name ? name : "tmp_field";
1553
append_identifier(thd, str, nm, (uint) strlen(nm));
1556
if (db_name && db_name[0] && !alias_name_used)
1559
append_identifier(thd, str, d_name, (uint)strlen(d_name));
1562
append_identifier(thd, str, t_name, (uint)strlen(t_name));
1564
append_identifier(thd, str, field_name, (uint)strlen(field_name));
1570
append_identifier(thd, str, t_name, (uint) strlen(t_name));
1572
append_identifier(thd, str, field_name, (uint) strlen(field_name));
1575
append_identifier(thd, str, field_name, (uint) strlen(field_name));
1580
String *Item_field::val_str(String *str)
1583
if ((null_value=field->is_null()))
1585
str->set_charset(str_value.charset());
1586
return field->val_str(str,&str_value);
1590
double Item_field::val_real()
1593
if ((null_value=field->is_null()))
1595
return field->val_real();
1599
longlong Item_field::val_int()
1602
if ((null_value=field->is_null()))
1604
return field->val_int();
1608
my_decimal *Item_field::val_decimal(my_decimal *decimal_value)
1610
if ((null_value= field->is_null()))
1612
return field->val_decimal(decimal_value);
1616
String *Item_field::str_result(String *str)
1618
if ((null_value=result_field->is_null()))
1620
str->set_charset(str_value.charset());
1621
return result_field->val_str(str,&str_value);
1624
bool Item_field::get_date(MYSQL_TIME *ltime,uint fuzzydate)
1626
if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
1628
bzero((char*) ltime,sizeof(*ltime));
1634
bool Item_field::get_date_result(MYSQL_TIME *ltime,uint fuzzydate)
1636
if ((null_value=result_field->is_null()) ||
1637
result_field->get_date(ltime,fuzzydate))
1639
bzero((char*) ltime,sizeof(*ltime));
1645
bool Item_field::get_time(MYSQL_TIME *ltime)
1647
if ((null_value=field->is_null()) || field->get_time(ltime))
1649
bzero((char*) ltime,sizeof(*ltime));
1655
double Item_field::val_result()
1657
if ((null_value=result_field->is_null()))
1659
return result_field->val_real();
1662
longlong Item_field::val_int_result()
1664
if ((null_value=result_field->is_null()))
1666
return result_field->val_int();
1670
my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value)
1672
if ((null_value= result_field->is_null()))
1674
return result_field->val_decimal(decimal_value);
1678
bool Item_field::val_bool_result()
1680
if ((null_value= result_field->is_null()))
1682
switch (result_field->result_type()) {
1684
return result_field->val_int() != 0;
1685
case DECIMAL_RESULT:
1687
my_decimal decimal_value;
1688
my_decimal *val= result_field->val_decimal(&decimal_value);
1690
return !my_decimal_is_zero(val);
1695
return result_field->val_real() != 0.0;
1699
return 0; // Shut up compiler
1704
bool Item_field::eq(const Item *item,
1705
bool binary_cmp __attribute__((__unused__))) const
1707
Item *real_item= ((Item *) item)->real_item();
1708
if (real_item->type() != FIELD_ITEM)
1711
Item_field *item_field= (Item_field*) real_item;
1712
if (item_field->field && field)
1713
return item_field->field == field;
1715
We may come here when we are trying to find a function in a GROUP BY
1716
clause from the select list.
1717
In this case the '100 % correct' way to do this would be to first
1718
run fix_fields() on the GROUP BY item and then retry this function, but
1719
I think it's better to relax the checking a bit as we will in
1720
most cases do the correct thing by just checking the field name.
1721
(In cases where we would choose wrong we would have to generate a
1724
return (!my_strcasecmp(system_charset_info, item_field->name,
1726
(!item_field->table_name || !table_name ||
1727
(!my_strcasecmp(table_alias_charset, item_field->table_name,
1729
(!item_field->db_name || !db_name ||
1730
(item_field->db_name && !strcmp(item_field->db_name,
1735
table_map Item_field::used_tables() const
1737
if (field->table->const_table)
1738
return 0; // const item
1739
return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
1743
void Item_field::fix_after_pullout(st_select_lex *new_parent,
1744
Item **ref __attribute__((__unused__)))
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 __attribute__((__unused__)),
1766
bool *incl_endp __attribute__((__unused__)))
1768
longlong res= val_int();
1769
return null_value? LONGLONG_MIN : res;
1773
Create an item from a string we KNOW points to a valid longlong
1774
end \\0 terminated number string.
1775
This is always 'signed'. Unsigned values are created with Item_uint()
1778
Item_int::Item_int(const char *str_arg, uint length)
1780
char *end_ptr= (char*) str_arg + length;
1782
value= my_strtoll10(str_arg, &end_ptr, &error);
1783
max_length= (uint) (end_ptr - str_arg);
1784
name= (char*) str_arg;
1789
my_decimal *Item_int::val_decimal(my_decimal *decimal_value)
1791
int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_value);
1792
return decimal_value;
1795
String *Item_int::val_str(String *str)
1797
// following assert is redundant, because fixed=1 assigned in constructor
1799
str->set(value, &my_charset_bin);
1803
void Item_int::print(String *str,
1804
enum_query_type query_type __attribute__((__unused__)))
1806
// my_charset_bin is good enough for numbers
1807
str_value.set(value, &my_charset_bin);
1808
str->append(str_value);
1812
Item_uint::Item_uint(const char *str_arg, uint length):
1813
Item_int(str_arg, length)
1819
Item_uint::Item_uint(const char *str_arg, longlong i, uint length):
1820
Item_int(str_arg, i, length)
1826
String *Item_uint::val_str(String *str)
1828
// following assert is redundant, because fixed=1 assigned in constructor
1830
str->set((ulonglong) value, &my_charset_bin);
1835
void Item_uint::print(String *str,
1836
enum_query_type query_type __attribute__((__unused__)))
1838
// latin1 is good enough for numbers
1839
str_value.set((ulonglong) value, default_charset());
1840
str->append(str_value);
1844
Item_decimal::Item_decimal(const char *str_arg, uint length,
1845
CHARSET_INFO *charset)
1847
str2my_decimal(E_DEC_FATAL_ERROR, str_arg, length, charset, &decimal_value);
1848
name= (char*) str_arg;
1849
decimals= (uint8) decimal_value.frac;
1851
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1852
decimals, unsigned_flag);
1855
Item_decimal::Item_decimal(longlong val, bool unsig)
1857
int2my_decimal(E_DEC_FATAL_ERROR, val, unsig, &decimal_value);
1858
decimals= (uint8) decimal_value.frac;
1860
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1861
decimals, unsigned_flag);
1865
Item_decimal::Item_decimal(double val,
1866
int precision __attribute__((__unused__)),
1867
int scale __attribute__((__unused__)))
1869
double2my_decimal(E_DEC_FATAL_ERROR, val, &decimal_value);
1870
decimals= (uint8) decimal_value.frac;
1872
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1873
decimals, unsigned_flag);
1877
Item_decimal::Item_decimal(const char *str, const my_decimal *val_arg,
1878
uint decimal_par, uint length)
1880
my_decimal2decimal(val_arg, &decimal_value);
1882
decimals= (uint8) decimal_par;
1888
Item_decimal::Item_decimal(my_decimal *value_par)
1890
my_decimal2decimal(value_par, &decimal_value);
1891
decimals= (uint8) decimal_value.frac;
1893
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1894
decimals, unsigned_flag);
1898
Item_decimal::Item_decimal(const uchar *bin, int precision, int scale)
1900
binary2my_decimal(E_DEC_FATAL_ERROR, bin,
1901
&decimal_value, precision, scale);
1902
decimals= (uint8) decimal_value.frac;
1904
max_length= my_decimal_precision_to_length(precision, decimals,
1909
longlong Item_decimal::val_int()
1912
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &result);
1916
double Item_decimal::val_real()
1919
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
1923
String *Item_decimal::val_str(String *result)
1925
result->set_charset(&my_charset_bin);
1926
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, result);
1930
void Item_decimal::print(String *str,
1931
enum_query_type query_type __attribute__((__unused__)))
1933
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, &str_value);
1934
str->append(str_value);
1938
bool Item_decimal::eq(const Item *item,
1939
bool binary_cmp __attribute__((__unused__))) const
1941
if (type() == item->type() && item->basic_const_item())
1944
We need to cast off const to call val_decimal(). This should
1945
be OK for a basic constant. Additionally, we can pass 0 as
1946
a true decimal constant will return its internal decimal
1947
storage and ignore the argument.
1949
Item *arg= (Item*) item;
1950
my_decimal *value= arg->val_decimal(0);
1951
return !my_decimal_cmp(&decimal_value, value);
1957
void Item_decimal::set_decimal_value(my_decimal *value_par)
1959
my_decimal2decimal(value_par, &decimal_value);
1960
decimals= (uint8) decimal_value.frac;
1961
unsigned_flag= !decimal_value.sign();
1962
max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
1963
decimals, unsigned_flag);
1967
String *Item_float::val_str(String *str)
1969
// following assert is redundant, because fixed=1 assigned in constructor
1971
str->set_real(value,decimals,&my_charset_bin);
1976
my_decimal *Item_float::val_decimal(my_decimal *decimal_value)
1978
// following assert is redundant, because fixed=1 assigned in constructor
1980
double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_value);
1981
return (decimal_value);
1985
void Item_string::print(String *str, enum_query_type query_type)
1987
if (query_type == QT_ORDINARY && is_cs_specified())
1990
str->append(collation.collation->csname);
1995
if (query_type == QT_ORDINARY ||
1996
my_charset_same(str_value.charset(), system_charset_info))
1998
str_value.print(str);
2002
THD *thd= current_thd;
2003
LEX_STRING utf8_lex_str;
2005
thd->convert_string(&utf8_lex_str,
2006
system_charset_info,
2007
str_value.c_ptr_safe(),
2009
str_value.charset());
2011
String utf8_str(utf8_lex_str.str,
2012
utf8_lex_str.length,
2013
system_charset_info);
2015
utf8_str.print(str);
2022
double Item_string::val_real()
2026
char *end, *org_end;
2028
CHARSET_INFO *cs= str_value.charset();
2030
org_end= (char*) str_value.ptr() + str_value.length();
2031
tmp= my_strntod(cs, (char*) str_value.ptr(), str_value.length(), &end,
2033
if (error || (end != org_end && !check_if_only_end_space(cs, end, org_end)))
2036
We can use str_value.ptr() here as Item_string is gurantee to put an
2039
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2040
ER_TRUNCATED_WRONG_VALUE,
2041
ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
2050
Give error if we wanted a signed integer and we got an unsigned one
2052
longlong Item_string::val_int()
2057
char *end= (char*) str_value.ptr()+ str_value.length();
2059
CHARSET_INFO *cs= str_value.charset();
2061
tmp= (*(cs->cset->strtoll10))(cs, str_value.ptr(), &end, &err);
2063
TODO: Give error if we wanted a signed integer and we got an unsigned
2067
(end != org_end && !check_if_only_end_space(cs, end, org_end)))
2069
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2070
ER_TRUNCATED_WRONG_VALUE,
2071
ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
2078
my_decimal *Item_string::val_decimal(my_decimal *decimal_value)
2080
return val_decimal_from_string(decimal_value);
2084
bool Item_null::eq(const Item *item,
2085
bool binary_cmp __attribute__((__unused__))) const
2086
{ return item->type() == type(); }
2089
double Item_null::val_real()
2091
// following assert is redundant, because fixed=1 assigned in constructor
2096
longlong Item_null::val_int()
2098
// following assert is redundant, because fixed=1 assigned in constructor
2104
String *Item_null::val_str(String *str __attribute__((__unused__)))
2106
// following assert is redundant, because fixed=1 assigned in constructor
2112
my_decimal *Item_null::val_decimal(my_decimal *decimal_value __attribute__((__unused__)))
2118
Item *Item_null::safe_charset_converter(CHARSET_INFO *tocs)
2120
collation.set(tocs);
2124
/*********************** Item_param related ******************************/
2127
Default function of Item_param::set_param_func, so in case
2128
of malformed packet the server won't SIGSEGV.
2132
default_set_param_func(Item_param *param,
2133
uchar **pos __attribute__((unused)),
2134
ulong len __attribute__((unused)))
2140
Item_param::Item_param(uint pos_in_query_arg) :
2142
item_result_type(STRING_RESULT),
2143
/* Don't pretend to be a literal unless value for this item is set. */
2144
item_type(PARAM_ITEM),
2145
param_type(MYSQL_TYPE_VARCHAR),
2146
pos_in_query(pos_in_query_arg),
2147
set_param_func(default_set_param_func),
2148
limit_clause_param(false)
2152
Since we can't say whenever this item can be NULL or cannot be NULL
2153
before mysql_stmt_execute(), so we assuming that it can be NULL until
2157
cnvitem= new Item_string("", 0, &my_charset_bin, DERIVATION_COERCIBLE);
2158
cnvstr.set(cnvbuf, sizeof(cnvbuf), &my_charset_bin);
2162
void Item_param::set_null()
2164
/* These are cleared after each execution by reset() method */
2167
Because of NULL and string values we need to set max_length for each new
2168
placeholder value: user can submit NULL for any placeholder type, and
2169
string length can be different in each execution.
2174
item_type= Item::NULL_ITEM;
2178
void Item_param::set_int(longlong i, uint32 max_length_arg)
2180
value.integer= (longlong) i;
2182
max_length= max_length_arg;
2188
void Item_param::set_double(double d)
2192
max_length= DBL_DIG + 8;
2193
decimals= NOT_FIXED_DEC;
2200
Set decimal parameter value from string.
2202
@param str character string
2203
@param length string length
2206
As we use character strings to send decimal values in
2207
binary protocol, we use str2my_decimal to convert it to
2208
internal decimal value.
2211
void Item_param::set_decimal(const char *str, ulong length)
2215
end= (char*) str+length;
2216
str2my_decimal(E_DEC_FATAL_ERROR, str, &decimal_value, &end);
2217
state= DECIMAL_VALUE;
2218
decimals= decimal_value.frac;
2219
max_length= my_decimal_precision_to_length(decimal_value.precision(),
2220
decimals, unsigned_flag);
2227
Set parameter value from MYSQL_TIME value.
2229
@param tm datetime value to set (time_type is ignored)
2230
@param type type of datetime value
2231
@param max_length_arg max length of datetime value as string
2234
If we value to be stored is not normalized, zero value will be stored
2235
instead and proper warning will be produced. This function relies on
2236
the fact that even wrong value sent over binary protocol fits into
2237
MAX_DATE_STRING_REP_LENGTH buffer.
2239
void Item_param::set_time(MYSQL_TIME *tm, timestamp_type time_type,
2240
uint32 max_length_arg)
2243
value.time.time_type= time_type;
2245
if (value.time.year > 9999 || value.time.month > 12 ||
2246
value.time.day > 31 ||
2247
((time_type != MYSQL_TIMESTAMP_TIME) && value.time.hour > 23) ||
2248
value.time.minute > 59 || value.time.second > 59)
2250
char buff[MAX_DATE_STRING_REP_LENGTH];
2251
uint length= my_TIME_to_str(&value.time, buff);
2252
make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2253
buff, length, time_type, 0);
2254
set_zero_time(&value.time, MYSQL_TIMESTAMP_ERROR);
2259
max_length= max_length_arg;
2265
bool Item_param::set_str(const char *str, ulong length)
2268
Assign string with no conversion: data is converted only after it's
2269
been written to the binary log.
2272
if (str_value.copy(str, length, &my_charset_bin, &my_charset_bin,
2275
state= STRING_VALUE;
2278
/* max_length and decimals are set after charset conversion */
2279
/* sic: str may be not null-terminated */
2284
bool Item_param::set_longdata(const char *str, ulong length)
2287
If client character set is multibyte, end of long data packet
2288
may hit at the middle of a multibyte character. Additionally,
2289
if binary log is open we must write long data value to the
2290
binary log in character set of client. This is why we can't
2291
convert long data to connection character set as it comes
2292
(here), and first have to concatenate all pieces together,
2293
write query to the binary log and only then perform conversion.
2295
if (str_value.append(str, length, &my_charset_bin))
2297
state= LONG_DATA_VALUE;
2305
Set parameter value from user variable value.
2307
@param thd Current thread
2308
@param entry User variable structure (NULL means use NULL value)
2316
bool Item_param::set_from_user_var(THD *thd, const user_var_entry *entry)
2318
if (entry && entry->value)
2320
item_result_type= entry->type;
2321
unsigned_flag= entry->unsigned_flag;
2322
if (limit_clause_param)
2325
set_int(entry->val_int(&unused), MY_INT64_NUM_DECIMAL_DIGITS);
2326
item_type= Item::INT_ITEM;
2327
return(!unsigned_flag && value.integer < 0 ? 1 : 0);
2329
switch (item_result_type) {
2331
set_double(*(double*)entry->value);
2332
item_type= Item::REAL_ITEM;
2335
set_int(*(longlong*)entry->value, MY_INT64_NUM_DECIMAL_DIGITS);
2336
item_type= Item::INT_ITEM;
2340
CHARSET_INFO *fromcs= entry->collation.collation;
2341
CHARSET_INFO *tocs= thd->variables.collation_connection;
2342
uint32 dummy_offset;
2344
value.cs_info.character_set_of_placeholder=
2345
value.cs_info.character_set_client= fromcs;
2347
Setup source and destination character sets so that they
2348
are different only if conversion is necessary: this will
2349
make later checks easier.
2351
value.cs_info.final_character_set_of_str_value=
2352
String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
2355
Exact value of max_length is not known unless data is converted to
2356
charset of connection, so we have to set it later.
2358
item_type= Item::STRING_ITEM;
2360
if (set_str((const char *)entry->value, entry->length))
2364
case DECIMAL_RESULT:
2366
const my_decimal *ent_value= (const my_decimal *)entry->value;
2367
my_decimal2decimal(ent_value, &decimal_value);
2368
state= DECIMAL_VALUE;
2369
decimals= ent_value->frac;
2370
max_length= my_decimal_precision_to_length(ent_value->precision(),
2371
decimals, unsigned_flag);
2372
item_type= Item::DECIMAL_ITEM;
2387
Resets parameter after execution.
2390
We clear null_value here instead of setting it in set_* methods,
2391
because we want more easily handle case for long data.
2394
void Item_param::reset()
2396
/* Shrink string buffer if it's bigger than max possible CHAR column */
2397
if (str_value.alloced_length() > MAX_CHAR_WIDTH)
2400
str_value.length(0);
2401
str_value_ptr.length(0);
2403
We must prevent all charset conversions until data has been written
2406
str_value.set_charset(&my_charset_bin);
2407
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
2412
Don't reset item_type to PARAM_ITEM: it's only needed to guard
2413
us from item optimizations at prepare stage, when item doesn't yet
2414
contain a literal of some kind.
2415
In all other cases when this object is accessed its value is
2416
set (this assumption is guarded by 'state' and
2417
assertS(state != NO_VALUE) in all Item_param::get_*
2424
int Item_param::save_in_field(Field *field, bool no_conversions)
2426
field->set_notnull();
2430
return field->store(value.integer, unsigned_flag);
2432
return field->store(value.real);
2434
return field->store_decimal(&decimal_value);
2436
field->store_time(&value.time, value.time.time_type);
2439
case LONG_DATA_VALUE:
2440
return field->store(str_value.ptr(), str_value.length(),
2441
str_value.charset());
2443
return set_field_to_null_with_conversions(field, no_conversions);
2452
bool Item_param::get_time(MYSQL_TIME *res)
2454
if (state == TIME_VALUE)
2460
If parameter value isn't supplied assertion will fire in val_str()
2461
which is called from Item::get_time().
2463
return Item::get_time(res);
2467
bool Item_param::get_date(MYSQL_TIME *res, uint fuzzydate)
2469
if (state == TIME_VALUE)
2474
return Item::get_date(res, fuzzydate);
2478
double Item_param::val_real()
2484
return (double) value.integer;
2488
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
2492
case LONG_DATA_VALUE:
2496
return my_strntod(str_value.charset(), (char*) str_value.ptr(),
2497
str_value.length(), &end_not_used, &dummy_err);
2501
This works for example when user says SELECT ?+0.0 and supplies
2502
time value for the placeholder.
2504
return ulonglong2double(TIME_to_ulonglong(&value.time));
2514
longlong Item_param::val_int()
2518
return (longlong) rint(value.real);
2520
return value.integer;
2524
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &i);
2528
case LONG_DATA_VALUE:
2531
return my_strntoll(str_value.charset(), str_value.ptr(),
2532
str_value.length(), 10, (char**) 0, &dummy_err);
2535
return (longlong) TIME_to_ulonglong(&value.time);
2545
my_decimal *Item_param::val_decimal(my_decimal *dec)
2549
return &decimal_value;
2551
double2my_decimal(E_DEC_FATAL_ERROR, value.real, dec);
2554
int2my_decimal(E_DEC_FATAL_ERROR, value.integer, unsigned_flag, dec);
2557
case LONG_DATA_VALUE:
2558
string2my_decimal(E_DEC_FATAL_ERROR, &str_value, dec);
2562
longlong i= (longlong) TIME_to_ulonglong(&value.time);
2563
int2my_decimal(E_DEC_FATAL_ERROR, i, 0, dec);
2575
String *Item_param::val_str(String* str)
2579
case LONG_DATA_VALUE:
2580
return &str_value_ptr;
2582
str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
2585
str->set(value.integer, &my_charset_bin);
2588
if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
2594
if (str->reserve(MAX_DATE_STRING_REP_LENGTH))
2596
str->length((uint) my_TIME_to_str(&value.time, (char*) str->ptr()));
2597
str->set_charset(&my_charset_bin);
2609
Return Param item values in string format, for generating the dynamic
2610
query used in update/binary logs.
2613
- Change interface and implementation to fill log data in place
2614
and avoid one more memcpy/alloc between str and log string.
2615
- In case of error we need to notify replication
2616
that binary log contains wrong statement
2619
const String *Item_param::query_val_str(String* str) const
2623
str->set_int(value.integer, unsigned_flag, &my_charset_bin);
2626
str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
2629
if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
2631
return &my_null_string;
2638
TODO: in case of error we need to notify replication
2639
that binary log contains wrong statement
2641
if (str->reserve(MAX_DATE_STRING_REP_LENGTH+3))
2644
/* Create date string inplace */
2645
buf= str->c_ptr_quick();
2648
ptr+= (uint) my_TIME_to_str(&value.time, ptr);
2650
str->length((uint32) (ptr - buf));
2654
case LONG_DATA_VALUE:
2657
append_query_string(value.cs_info.character_set_client, &str_value, str);
2661
return &my_null_string;
2670
Convert string from client character set to the character set of
2674
bool Item_param::convert_str_value(THD *thd)
2677
if (state == STRING_VALUE || state == LONG_DATA_VALUE)
2680
Check is so simple because all charsets were set up properly
2681
in setup_one_conversion_function, where typecode of
2682
placeholder was also taken into account: the variables are different
2683
here only if conversion is really necessary.
2685
if (value.cs_info.final_character_set_of_str_value !=
2686
value.cs_info.character_set_of_placeholder)
2688
rc= thd->convert_string(&str_value,
2689
value.cs_info.character_set_of_placeholder,
2690
value.cs_info.final_character_set_of_str_value);
2693
str_value.set_charset(value.cs_info.final_character_set_of_str_value);
2694
/* Here str_value is guaranteed to be in final_character_set_of_str_value */
2696
max_length= str_value.length();
2699
str_value_ptr is returned from val_str(). It must be not alloced
2700
to prevent it's modification by val_str() invoker.
2702
str_value_ptr.set(str_value.ptr(), str_value.length(),
2703
str_value.charset());
2704
/* Synchronize item charset with value charset */
2705
collation.set(str_value.charset(), DERIVATION_COERCIBLE);
2711
bool Item_param::basic_const_item() const
2713
if (state == NO_VALUE || state == TIME_VALUE)
2720
Item_param::clone_item()
2722
/* see comments in the header file */
2725
return new Item_null(name);
2727
return (unsigned_flag ?
2728
new Item_uint(name, value.integer, max_length) :
2729
new Item_int(name, value.integer, max_length));
2731
return new Item_float(name, value.real, decimals, max_length);
2733
case LONG_DATA_VALUE:
2734
return new Item_string(name, str_value.c_ptr_quick(), str_value.length(),
2735
str_value.charset());
2747
Item_param::eq(const Item *arg, bool binary_cmp) const
2750
if (!basic_const_item() || !arg->basic_const_item() || arg->type() != type())
2753
We need to cast off const to call val_int(). This should be OK for
2762
return value.integer == item->val_int() &&
2763
unsigned_flag == item->unsigned_flag;
2765
return value.real == item->val_real();
2767
case LONG_DATA_VALUE:
2769
return !stringcmp(&str_value, &item->str_value);
2770
return !sortcmp(&str_value, &item->str_value, collation.collation);
2777
/* End of Item_param related */
2779
void Item_param::print(String *str,
2780
enum_query_type query_type __attribute__((__unused__)))
2782
if (state == NO_VALUE)
2788
char buffer[STRING_BUFFER_USUAL_SIZE];
2789
String tmp(buffer, sizeof(buffer), &my_charset_bin);
2791
res= query_val_str(&tmp);
2797
/****************************************************************************
2799
****************************************************************************/
2801
void Item_copy_string::copy()
2803
String *res=item->val_str(&str_value);
2804
if (res && res != &str_value)
2805
str_value.copy(*res);
2806
null_value=item->null_value;
2810
String *Item_copy_string::val_str(String *str __attribute__((__unused__)))
2812
// Item_copy_string is used without fix_fields call
2819
my_decimal *Item_copy_string::val_decimal(my_decimal *decimal_value)
2821
// Item_copy_string is used without fix_fields call
2824
string2my_decimal(E_DEC_FATAL_ERROR, &str_value, decimal_value);
2825
return (decimal_value);
771
2830
Functions to convert item to field (for send_fields)
773
bool Item::fix_fields(Session *, Item **)
2834
bool Item::fix_fields(THD *thd __attribute__((__unused__)),
2835
Item **ref __attribute__((__unused__)))
775
/* We do not check fields which are fixed during construction */
776
assert(! fixed || basic_const_item());
2838
// We do not check fields which are fixed during construction
2839
assert(fixed == 0 || basic_const_item());
781
void mark_as_dependent(Session *session, Select_Lex *last, Select_Lex *current,
2844
double Item_ref_null_helper::val_real()
2847
double tmp= (*ref)->val_result();
2848
owner->was_null|= null_value= (*ref)->null_value;
2853
longlong Item_ref_null_helper::val_int()
2856
longlong tmp= (*ref)->val_int_result();
2857
owner->was_null|= null_value= (*ref)->null_value;
2862
my_decimal *Item_ref_null_helper::val_decimal(my_decimal *decimal_value)
2865
my_decimal *val= (*ref)->val_decimal_result(decimal_value);
2866
owner->was_null|= null_value= (*ref)->null_value;
2871
bool Item_ref_null_helper::val_bool()
2874
bool val= (*ref)->val_bool_result();
2875
owner->was_null|= null_value= (*ref)->null_value;
2880
String* Item_ref_null_helper::val_str(String* s)
2883
String* tmp= (*ref)->str_result(s);
2884
owner->was_null|= null_value= (*ref)->null_value;
2889
bool Item_ref_null_helper::get_date(MYSQL_TIME *ltime, uint fuzzydate)
2891
return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate));
2896
Mark item and SELECT_LEXs as dependent if item was resolved in
2899
@param thd thread handler
2900
@param last select from which current item depend
2901
@param current current select
2902
@param resolved_item item which was resolved in outer SELECT(for warning)
2903
@param mark_item item which should be marked (can be differ in case of
2907
static void mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current,
782
2908
Item_ident *resolved_item,
783
2909
Item_ident *mark_item)
1006
3197
return (Item**) not_found_item;
1009
void Item::init_make_field(SendField *tmp_field,
3202
Resolve the name of an outer select column reference.
3204
The method resolves the column reference represented by 'this' as a column
3205
present in outer selects that contain current select.
3207
In prepared statements, because of cache, find_field_in_tables()
3208
can resolve fields even if they don't belong to current context.
3209
In this case this method only finds appropriate context and marks
3210
current select as dependent. The found reference of field should be
3211
provided in 'from_field'.
3213
@param[in] thd current thread
3214
@param[in,out] from_field found field reference or (Field*)not_found_field
3215
@param[in,out] reference view column if this item was resolved to a
3219
This is the inner loop of Item_field::fix_fields:
3221
for each outer query Q_k beginning from the inner-most one
3223
search for a column or derived column named col_ref_i
3224
[in table T_j] in the FROM clause of Q_k;
3226
if such a column is not found
3227
Search for a column or derived column named col_ref_i
3228
[in table T_j] in the SELECT and GROUP clauses of Q_k.
3233
1 column succefully resolved and fix_fields() should continue.
3235
0 column fully fixed and fix_fields() should return false
3241
Item_field::fix_outer_field(THD *thd, Field **from_field, Item **reference)
3243
enum_parsing_place place= NO_MATTER;
3244
bool field_found= (*from_field != not_found_field);
3245
bool upward_lookup= false;
3248
If there are outer contexts (outer selects, but current select is
3249
not derived table or view) try to resolve this reference in the
3252
We treat each subselect as a separate namespace, so that different
3253
subselects may contain columns with the same names. The subselects
3254
are searched starting from the innermost.
3256
Name_resolution_context *last_checked_context= context;
3257
Item **ref= (Item **) not_found_item;
3258
SELECT_LEX *current_sel= (SELECT_LEX *) thd->lex->current_select;
3259
Name_resolution_context *outer_context= 0;
3260
SELECT_LEX *select= 0;
3261
/* Currently derived tables cannot be correlated */
3262
if (current_sel->master_unit()->first_select()->linkage !=
3264
outer_context= context->outer_context;
3267
outer_context= outer_context->outer_context)
3269
select= outer_context->select_lex;
3270
Item_subselect *prev_subselect_item=
3271
last_checked_context->select_lex->master_unit()->item;
3272
last_checked_context= outer_context;
3273
upward_lookup= true;
3275
place= prev_subselect_item->parsing_place;
3277
If outer_field is set, field was already found by first call
3278
to find_field_in_tables(). Only need to find appropriate context.
3280
if (field_found && outer_context->select_lex !=
3281
cached_table->select_lex)
3284
In case of a view, find_field_in_tables() writes the pointer to
3285
the found view field into '*reference', in other words, it
3286
substitutes this Item_field with the found expression.
3288
if (field_found || (*from_field= find_field_in_tables(thd, this,
3290
first_name_resolution_table,
3292
last_name_resolution_table,
3294
IGNORE_EXCEPT_NON_UNIQUE,
3300
if (*from_field != view_ref_found)
3302
prev_subselect_item->used_tables_cache|= (*from_field)->table->map;
3303
prev_subselect_item->const_item_cache= 0;
3304
set_field(*from_field);
3305
if (!last_checked_context->select_lex->having_fix_field &&
3306
select->group_list.elements &&
3307
(place == SELECT_LIST || place == IN_HAVING))
3311
If an outer field is resolved in a grouping select then it
3312
is replaced for an Item_outer_ref object. Otherwise an
3313
Item_field object is used.
3314
The new Item_outer_ref object is saved in the inner_refs_list of
3315
the outer select. Here it is only created. It can be fixed only
3316
after the original field has been fixed and this is done in the
3317
fix_inner_refs() function.
3320
if (!(rf= new Item_outer_ref(context, this)))
3322
thd->change_item_tree(reference, rf);
3323
select->inner_refs_list.push_back(rf);
3324
rf->in_sum_func= thd->lex->in_sum_func;
3327
A reference is resolved to a nest level that's outer or the same as
3328
the nest level of the enclosing set function : adjust the value of
3329
max_arg_level for the function if it's needed.
3331
if (thd->lex->in_sum_func &&
3332
thd->lex->in_sum_func->nest_level >= select->nest_level)
3334
Item::Type ref_type= (*reference)->type();
3335
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
3336
select->nest_level);
3337
set_field(*from_field);
3339
mark_as_dependent(thd, last_checked_context->select_lex,
3340
context->select_lex, this,
3341
((ref_type == REF_ITEM ||
3342
ref_type == FIELD_ITEM) ?
3343
(Item_ident*) (*reference) : 0));
3349
Item::Type ref_type= (*reference)->type();
3350
prev_subselect_item->used_tables_cache|=
3351
(*reference)->used_tables();
3352
prev_subselect_item->const_item_cache&=
3353
(*reference)->const_item();
3354
mark_as_dependent(thd, last_checked_context->select_lex,
3355
context->select_lex, this,
3356
((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ?
3357
(Item_ident*) (*reference) :
3360
A reference to a view field had been found and we
3361
substituted it instead of this Item (find_field_in_tables
3362
does it by assigning the new value to *reference), so now
3363
we can return from this function.
3371
/* Search in SELECT and GROUP lists of the outer select. */
3372
if (place != IN_WHERE && place != IN_ON)
3374
if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
3375
return -1; /* Some error occurred (e.g. ambiguous names). */
3376
if (ref != not_found_item)
3378
assert(*ref && (*ref)->fixed);
3379
prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
3380
prev_subselect_item->const_item_cache&= (*ref)->const_item();
3386
Reference is not found in this select => this subquery depend on
3387
outer select (or we just trying to find wrong identifier, in this
3388
case it does not matter which used tables bits we set)
3390
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
3391
prev_subselect_item->const_item_cache= 0;
3397
if (ref == not_found_item && *from_field == not_found_field)
3401
// We can't say exactly what absent table or field
3402
my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where);
3406
/* Call find_field_in_tables only to report the error */
3407
find_field_in_tables(thd, this,
3408
context->first_name_resolution_table,
3409
context->last_name_resolution_table,
3410
reference, REPORT_ALL_ERRORS,
3416
else if (ref != not_found_item)
3421
/* Should have been checked in resolve_ref_in_select_and_group(). */
3422
assert(*ref && (*ref)->fixed);
3424
Here, a subset of actions performed by Item_ref::set_properties
3425
is not enough. So we pass ptr to NULL into Item_[direct]_ref
3426
constructor, so no initialization is performed, and call
3430
*ref= NULL; // Don't call set_properties()
3431
rf= (place == IN_HAVING ?
3432
new Item_ref(context, ref, (char*) table_name,
3433
(char*) field_name, alias_name_used) :
3434
(!select->group_list.elements ?
3435
new Item_direct_ref(context, ref, (char*) table_name,
3436
(char*) field_name, alias_name_used) :
3437
new Item_outer_ref(context, ref, (char*) table_name,
3438
(char*) field_name, alias_name_used)));
3443
if (place != IN_HAVING && select->group_list.elements)
3445
outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf);
3446
((Item_outer_ref*)rf)->in_sum_func= thd->lex->in_sum_func;
3448
thd->change_item_tree(reference, rf);
3450
rf is Item_ref => never substitute other items (in this case)
3451
during fix_fields() => we can use rf after fix_fields()
3453
assert(!rf->fixed); // Assured by Item_ref()
3454
if (rf->fix_fields(thd, reference) || rf->check_cols(1))
3457
mark_as_dependent(thd, last_checked_context->select_lex,
3458
context->select_lex, this,
3464
mark_as_dependent(thd, last_checked_context->select_lex,
3465
context->select_lex,
3466
this, (Item_ident*)*reference);
3467
if (last_checked_context->select_lex->having_fix_field)
3470
rf= new Item_ref(context,
3471
(cached_table->db[0] ? cached_table->db : 0),
3472
(char*) cached_table->alias, (char*) field_name);
3475
thd->change_item_tree(reference, rf);
3477
rf is Item_ref => never substitute other items (in this case)
3478
during fix_fields() => we can use rf after fix_fields()
3480
assert(!rf->fixed); // Assured by Item_ref()
3481
if (rf->fix_fields(thd, reference) || rf->check_cols(1))
3491
Resolve the name of a column reference.
3493
The method resolves the column reference represented by 'this' as a column
3494
present in one of: FROM clause, SELECT clause, GROUP BY clause of a query
3495
Q, or in outer queries that contain Q.
3497
The name resolution algorithm used is (where [T_j] is an optional table
3498
name that qualifies the column name):
3501
resolve_column_reference([T_j].col_ref_i)
3503
search for a column or derived column named col_ref_i
3504
[in table T_j] in the FROM clause of Q;
3506
if such a column is NOT found AND // Lookup in outer queries.
3507
there are outer queries
3509
for each outer query Q_k beginning from the inner-most one
3511
search for a column or derived column named col_ref_i
3512
[in table T_j] in the FROM clause of Q_k;
3514
if such a column is not found
3515
Search for a column or derived column named col_ref_i
3516
[in table T_j] in the SELECT and GROUP clauses of Q_k.
3522
Notice that compared to Item_ref::fix_fields, here we first search the FROM
3523
clause, and then we search the SELECT and GROUP BY clauses.
3525
@param[in] thd current thread
3526
@param[in,out] reference view column if this item was resolved to a
3535
bool Item_field::fix_fields(THD *thd, Item **reference)
3538
Field *from_field= (Field *)not_found_field;
3539
bool outer_fixed= false;
3541
if (!field) // If field is not checked
3544
In case of view, find_field_in_tables() write pointer to view field
3545
expression to 'reference', i.e. it substitute that expression instead
3548
if ((from_field= find_field_in_tables(thd, this,
3549
context->first_name_resolution_table,
3550
context->last_name_resolution_table,
3552
thd->lex->use_only_table_context ?
3554
IGNORE_EXCEPT_NON_UNIQUE,
3560
/* Look up in current select's item_list to find aliased fields */
3561
if (thd->lex->current_select->is_item_list_lookup)
3564
enum_resolution_type resolution;
3565
Item** res= find_item_in_list(this, thd->lex->current_select->item_list,
3566
&counter, REPORT_EXCEPT_NOT_FOUND,
3570
if (resolution == RESOLVED_AGAINST_ALIAS)
3571
alias_name_used= true;
3572
if (res != (Item **)not_found_item)
3574
if ((*res)->type() == Item::FIELD_ITEM)
3577
It's an Item_field referencing another Item_field in the select
3579
Use the field from the Item_field in the select list and leave
3580
the Item_field instance in place.
3583
Field *new_field= (*((Item_field**)res))->field;
3585
if (new_field == NULL)
3587
/* The column to which we link isn't valid. */
3588
my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->name,
3589
current_thd->where);
3593
set_field(new_field);
3599
It's not an Item_field in the select list so we must make a new
3600
Item_ref to point to the Item in the select list and replace the
3601
Item_field created by the parser with the new Item_ref.
3603
Item_ref *rf= new Item_ref(context, db_name,table_name,field_name);
3606
thd->change_item_tree(reference, rf);
3608
Because Item_ref never substitutes itself with other items
3609
in Item_ref::fix_fields(), we can safely use the original
3610
pointer to it even after fix_fields()
3612
return rf->fix_fields(thd, reference) || rf->check_cols(1);
3616
if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
3620
goto mark_non_agg_field;
3622
else if (!from_field)
3625
if (!outer_fixed && cached_table && cached_table->select_lex &&
3626
context->select_lex &&
3627
cached_table->select_lex != context->select_lex)
3630
if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
3634
goto mark_non_agg_field;
3638
if it is not expression from merged VIEW we will set this field.
3640
We can leave expression substituted from view for next PS/SP rexecution
3641
(i.e. do not register this substitution for reverting on cleanup()
3642
(register_item_tree_changing())), because this subtree will be
3643
fix_field'ed during setup_tables()->setup_underlying() (i.e. before
3644
all other expressions of query, and references on tables which do
3645
not present in query will not make problems.
3647
Also we suppose that view can't be changed during PS/SP life.
3649
if (from_field == view_ref_found)
3652
set_field(from_field);
3653
if (thd->lex->in_sum_func &&
3654
thd->lex->in_sum_func->nest_level ==
3655
thd->lex->current_select->nest_level)
3656
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
3657
thd->lex->current_select->nest_level);
3659
else if (thd->mark_used_columns != MARK_COLUMNS_NONE)
3661
TABLE *table= field->table;
3662
MY_BITMAP *current_bitmap, *other_bitmap;
3663
if (thd->mark_used_columns == MARK_COLUMNS_READ)
3665
current_bitmap= table->read_set;
3666
other_bitmap= table->write_set;
3670
current_bitmap= table->write_set;
3671
other_bitmap= table->read_set;
3673
if (!bitmap_fast_test_and_set(current_bitmap, field->field_index))
3675
if (!bitmap_is_set(other_bitmap, field->field_index))
3677
/* First usage of column */
3678
table->used_fields++; // Used to optimize loops
3679
/* purecov: begin inspected */
3680
table->covering_keys.intersect(field->part_of_key);
3690
context->process_error(thd);
3694
Item *Item_field::safe_charset_converter(CHARSET_INFO *tocs)
3697
return Item::safe_charset_converter(tocs);
3701
void Item_field::cleanup()
3703
Item_ident::cleanup();
3705
Even if this object was created by direct link to field in setup_wild()
3706
it will be linked correctly next time by name of field and table alias.
3707
I.e. we can drop 'field'.
3709
field= result_field= 0;
3715
Find a field among specified multiple equalities.
3717
The function first searches the field among multiple equalities
3718
of the current level (in the cond_equal->current_level list).
3719
If it fails, it continues searching in upper levels accessed
3720
through a pointer cond_equal->upper_levels.
3721
The search terminates as soon as a multiple equality containing
3724
@param cond_equal reference to list of multiple equalities where
3725
the field (this object) is to be looked for
3728
- First Item_equal containing the field, if success
3732
Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal)
3734
Item_equal *item= 0;
3737
List_iterator_fast<Item_equal> li(cond_equal->current_level);
3738
while ((item= li++))
3740
if (item->contains(field))
3744
The field is not found in any of the multiple equalities
3745
of the current level. Look for it in upper levels
3747
cond_equal= cond_equal->upper_levels;
3754
Check whether a field can be substituted by an equal item.
3756
The function checks whether a substitution of the field
3757
occurrence for an equal item is valid.
3759
@param arg *arg != NULL <-> the field is in the context where
3760
substitution for an equal item is valid
3763
The following statement is not always true:
3767
This means substitution of an item for an equal item not always
3768
yields an equavalent condition. Here's an example:
3771
(LENGTH('a')=1) != (LENGTH('a ')=2)
3773
Such a substitution is surely valid if either the substituted
3774
field is not of a STRING type or if it is an argument of
3775
a comparison predicate.
3778
true substitution is valid
3783
bool Item_field::subst_argument_checker(uchar **arg)
3785
return (result_type() != STRING_RESULT) || (*arg);
3790
Convert a numeric value to a zero-filled string
3792
@param[in,out] item the item to operate on
3793
@param field The field that this value is equated to
3795
This function converts a numeric value to a string. In this conversion
3796
the zero-fill flag of the field is taken into account.
3797
This is required so the resulting string value can be used instead of
3798
the field reference when propagating equalities.
3801
static void convert_zerofill_number_to_string(Item **item, Field_num *field)
3803
char buff[MAX_FIELD_WIDTH],*pos;
3804
String tmp(buff,sizeof(buff), field->charset()), *res;
3806
res= (*item)->val_str(&tmp);
3807
field->prepend_zeros(res);
3808
pos= (char *) sql_strmake (res->ptr(), res->length());
3809
*item= new Item_string(pos, res->length(), field->charset());
3814
Set a pointer to the multiple equality the field reference belongs to
3817
The function looks for a multiple equality containing the field item
3818
among those referenced by arg.
3819
In the case such equality exists the function does the following.
3820
If the found multiple equality contains a constant, then the field
3821
reference is substituted for this constant, otherwise it sets a pointer
3822
to the multiple equality in the field item.
3825
@param arg reference to list of multiple equalities where
3826
the field (this object) is to be looked for
3829
This function is supposed to be called as a callback parameter in calls
3830
of the compile method.
3833
- pointer to the replacing constant item, if the field item was substituted
3834
- pointer to the field item, otherwise.
3837
Item *Item_field::equal_fields_propagator(uchar *arg)
3841
item_equal= find_item_equal((COND_EQUAL *) arg);
3844
item= item_equal->get_const();
3846
Disable const propagation for items used in different comparison contexts.
3847
This must be done because, for example, Item_hex_string->val_int() is not
3848
the same as (Item_hex_string->val_str() in BINARY column)->val_int().
3849
We cannot simply disable the replacement in a particular context (
3850
e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
3851
Items don't know the context they are in and there are functions like
3852
IF (<hex_string>, 'yes', 'no').
3853
The same problem occurs when comparing a DATE/TIME field with a
3854
DATE/TIME represented as an int and as a string.
3857
(cmp_context != (Item_result)-1 && item->cmp_context != cmp_context))
3859
else if (field && (field->flags & ZEROFILL_FLAG) && IS_NUM(field->type()))
3861
if (item && cmp_context != INT_RESULT)
3862
convert_zerofill_number_to_string(&item, (Field_num *)field);
3871
Mark the item to not be part of substitution if it's not a binary item.
3873
See comments in Arg_comparator::set_compare_func() for details.
3876
bool Item_field::set_no_const_sub(uchar *arg __attribute__((__unused__)))
3878
if (field->charset() != &my_charset_bin)
3885
Replace an Item_field for an equal Item_field that evaluated earlier
3888
The function returns a pointer to an item that is taken from
3889
the very beginning of the item_equal list which the Item_field
3890
object refers to (belongs to) unless item_equal contains a constant
3891
item. In this case the function returns this constant item,
3892
(if the substitution does not require conversion).
3893
If the Item_field object does not refer any Item_equal object
3894
'this' is returned .
3896
@param arg a dummy parameter, is not used here
3900
This function is supposed to be called as a callback parameter in calls
3901
of the thransformer method.
3904
- pointer to a replacement Item_field if there is a better equal item or
3905
a pointer to a constant equal item;
3909
Item *Item_field::replace_equal_field(uchar *arg __attribute__((__unused__)))
3913
Item *const_item= item_equal->get_const();
3916
if (cmp_context != (Item_result)-1 &&
3917
const_item->cmp_context != cmp_context)
3921
Item_field *subst= item_equal->get_first();
3922
if (subst && !field->eq(subst->field))
3929
void Item::init_make_field(Send_field *tmp_field,
1010
3930
enum enum_field_types field_type_arg)
1012
3932
char *empty_name= (char*) "";
1013
tmp_field->db_name= empty_name;
1014
tmp_field->org_table_name= empty_name;
1015
tmp_field->org_col_name= empty_name;
1016
tmp_field->table_name= empty_name;
1017
tmp_field->col_name= name;
1018
tmp_field->charsetnr= collation.collation->number;
1019
tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
1020
(my_binary_compare(collation.collation) ?
1022
tmp_field->type= field_type_arg;
1023
tmp_field->length= max_length;
1024
tmp_field->decimals= decimals;
3933
tmp_field->db_name= empty_name;
3934
tmp_field->org_table_name= empty_name;
3935
tmp_field->org_col_name= empty_name;
3936
tmp_field->table_name= empty_name;
3937
tmp_field->col_name= name;
3938
tmp_field->charsetnr= collation.collation->number;
3939
tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
3940
(my_binary_compare(collation.collation) ?
3942
tmp_field->type= field_type_arg;
3943
tmp_field->length=max_length;
3944
tmp_field->decimals=decimals;
3946
tmp_field->flags |= UNSIGNED_FLAG;
1027
void Item::make_field(SendField *tmp_field)
3949
void Item::make_field(Send_field *tmp_field)
1029
3951
init_make_field(tmp_field, field_type());
1032
3955
enum_field_types Item::string_field_type() const
1034
enum_field_types f_type= DRIZZLE_TYPE_VARCHAR;
3957
enum_field_types f_type= MYSQL_TYPE_VAR_STRING;
1035
3958
if (max_length >= 65536)
1036
f_type= DRIZZLE_TYPE_BLOB;
3959
f_type= MYSQL_TYPE_BLOB;
3964
void Item_empty_string::make_field(Send_field *tmp_field)
3966
init_make_field(tmp_field, string_field_type());
1040
3970
enum_field_types Item::field_type() const
1042
3972
switch (result_type()) {
1044
return string_field_type();
1046
return DRIZZLE_TYPE_LONGLONG;
1047
case DECIMAL_RESULT:
1048
return DRIZZLE_TYPE_DECIMAL;
1050
return DRIZZLE_TYPE_DOUBLE;
3973
case STRING_RESULT: return string_field_type();
3974
case INT_RESULT: return MYSQL_TYPE_LONGLONG;
3975
case DECIMAL_RESULT: return MYSQL_TYPE_NEWDECIMAL;
3976
case REAL_RESULT: return MYSQL_TYPE_DOUBLE;
1051
3977
case ROW_RESULT:
3980
return MYSQL_TYPE_VARCHAR;
1058
3985
bool Item::is_datetime()
1060
3987
switch (field_type())
1062
case DRIZZLE_TYPE_DATE:
1063
case DRIZZLE_TYPE_DATETIME:
1064
case DRIZZLE_TYPE_TIMESTAMP:
3989
case MYSQL_TYPE_NEWDATE:
3990
case MYSQL_TYPE_DATETIME:
3991
case MYSQL_TYPE_TIMESTAMP:
1066
case DRIZZLE_TYPE_BLOB:
1067
case DRIZZLE_TYPE_VARCHAR:
1068
case DRIZZLE_TYPE_DOUBLE:
1069
case DRIZZLE_TYPE_DECIMAL:
1070
case DRIZZLE_TYPE_ENUM:
1071
case DRIZZLE_TYPE_LONG:
1072
case DRIZZLE_TYPE_LONGLONG:
1073
case DRIZZLE_TYPE_NULL:
1074
case DRIZZLE_TYPE_UUID:
1082
4000
String *Item::check_well_formed_result(String *str, bool send_error)
1084
4002
/* Check whether we got a well-formed string */
1085
const CHARSET_INFO * const cs= str->charset();
4003
CHARSET_INFO *cs= str->charset();
1086
4004
int well_formed_error;
1087
uint32_t wlen= cs->cset->well_formed_len(cs,
4005
uint wlen= cs->cset->well_formed_len(cs,
1088
4006
str->ptr(), str->ptr() + str->length(),
1089
4007
str->length(), &well_formed_error);
1090
4008
if (wlen < str->length())
1092
Session *session= current_session;
4010
THD *thd= current_thd;
1093
4011
char hexbuf[7];
1094
enum DRIZZLE_ERROR::enum_warning_level level;
1095
uint32_t diff= str->length() - wlen;
1096
set_if_smaller(diff, 3U);
1097
(void) drizzled_string_to_hex(hexbuf, str->ptr() + wlen, diff);
4012
enum MYSQL_ERROR::enum_warning_level level;
4013
uint diff= str->length() - wlen;
4014
set_if_smaller(diff, 3);
4015
octet2hex(hexbuf, str->ptr() + wlen, diff);
1098
4016
if (send_error)
1100
4018
my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
1101
4019
cs->csname, hexbuf);
1105
level= DRIZZLE_ERROR::WARN_LEVEL_ERROR;
4023
level= MYSQL_ERROR::WARN_LEVEL_ERROR;
1109
push_warning_printf(session, level, ER_INVALID_CHARACTER_STRING,
4027
push_warning_printf(thd, level, ER_INVALID_CHARACTER_STRING,
1110
4028
ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
1115
bool Item::eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO * const cs)
4034
Compare two items using a given collation
4038
item item to compare with
4039
binary_cmp true <-> compare as binaries
4040
cs collation to use when comparing strings
4043
This method works exactly as Item::eq if the collation cs coincides with
4044
the collation of the compared objects. Otherwise, first the collations that
4045
differ from cs are replaced for cs and then the items are compared by
4046
Item::eq. After the comparison the original collations of items are
4050
1 compared items has been detected as equal
4054
bool Item::eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs)
1117
const CHARSET_INFO *save_cs= 0;
1118
const CHARSET_INFO *save_item_cs= 0;
4056
CHARSET_INFO *save_cs= 0;
4057
CHARSET_INFO *save_item_cs= 0;
1119
4058
if (collation.collation != cs)
1121
4060
save_cs= collation.collation;
1280
Check if an item is a constant one and can be cached.
1282
@param arg [out] TRUE <=> Cache this item.
1284
@return TRUE Go deeper in item tree.
1285
@return FALSE Don't go deeper in item tree.
1288
bool Item::cache_const_expr_analyzer(unsigned char **arg)
1290
bool *cache_flag= (bool*)*arg;
1293
Item *item= real_item();
1295
Cache constant items unless it's a basic constant, constant field or
1296
a subselect (they use their own cache).
1299
!(item->basic_const_item() || item->type() == Item::FIELD_ITEM ||
1300
item->type() == SUBSELECT_ITEM ||
1302
Do not cache GET_USER_VAR() function as its const_item() may
1303
return TRUE for the current thread but it still may change
1304
during the execution.
1306
(item->type() == Item::FUNC_ITEM &&
1307
((Item_func*)item)->functype() == Item_func::GUSERVAR_FUNC)))
1315
Cache item if needed.
1317
@param arg TRUE <=> Cache this item.
1319
@return cache if cache needed.
1320
@return this otherwise.
1323
Item* Item::cache_const_expr_transformer(unsigned char *arg)
1327
*((bool*)arg)= false;
1328
Item_cache *cache= Item_cache::get_cache(this);
1338
bool Item::send(plugin::Client *client, String *buffer)
4363
int Item_string::save_in_field(Field *field,
4364
bool no_conversions __attribute__((__unused__)))
4367
result=val_str(&str_value);
4368
return save_str_value_in_field(field, result);
4372
int Item_uint::save_in_field(Field *field, bool no_conversions)
4374
/* Item_int::save_in_field handles both signed and unsigned. */
4375
return Item_int::save_in_field(field, no_conversions);
4379
int Item_int::save_in_field(Field *field,
4380
bool no_conversions __attribute__((__unused__)))
4382
longlong nr=val_int();
4384
return set_field_to_null(field);
4385
field->set_notnull();
4386
return field->store(nr, unsigned_flag);
4390
int Item_decimal::save_in_field(Field *field,
4391
bool no_conversions __attribute__((__unused__)))
4393
field->set_notnull();
4394
return field->store_decimal(&decimal_value);
4398
bool Item_int::eq(const Item *arg,
4399
bool binary_cmp __attribute__((__unused__))) const
4401
/* No need to check for null value as basic constant can't be NULL */
4402
if (arg->basic_const_item() && arg->type() == type())
4405
We need to cast off const to call val_int(). This should be OK for
4408
Item *item= (Item*) arg;
4409
return item->val_int() == value && item->unsigned_flag == unsigned_flag;
4415
Item *Item_int_with_ref::clone_item()
4417
assert(ref->const_item());
4419
We need to evaluate the constant to make sure it works with
4422
return (ref->unsigned_flag ?
4423
new Item_uint(ref->name, ref->val_int(), ref->max_length) :
4424
new Item_int(ref->name, ref->val_int(), ref->max_length));
4428
Item_num *Item_uint::neg()
4430
Item_decimal *item= new Item_decimal(value, 1);
4435
static uint nr_of_decimals(const char *str, const char *end)
4437
const char *decimal_point;
4439
/* Find position for '.' */
4444
if (*str == 'e' || *str == 'E')
4445
return NOT_FIXED_DEC;
4450
for (; my_isdigit(system_charset_info, *str) ; str++)
4452
if (*str == 'e' || *str == 'E')
4453
return NOT_FIXED_DEC;
4454
return (uint) (str - decimal_point);
4459
This function is only called during parsing. We will signal an error if
4460
value is not a true double value (overflow)
4463
Item_float::Item_float(const char *str_arg, uint length)
4467
value= my_strntod(&my_charset_bin, (char*) str_arg, length, &end_not_used,
4472
Note that we depend on that str_arg is null terminated, which is true
4473
when we are in the parser
4475
assert(str_arg[length] == 0);
4476
my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", (char*) str_arg);
4478
presentation= name=(char*) str_arg;
4479
decimals=(uint8) nr_of_decimals(str_arg, str_arg+length);
4485
int Item_float::save_in_field(Field *field,
4486
bool no_conversions __attribute__((__unused__)))
4488
double nr= val_real();
4490
return set_field_to_null(field);
4491
field->set_notnull();
4492
return field->store(nr);
4496
void Item_float::print(String *str,
4497
enum_query_type query_type __attribute__((__unused__)))
4501
str->append(presentation);
4505
String num(buffer, sizeof(buffer), &my_charset_bin);
4506
num.set_real(value, decimals, &my_charset_bin);
4513
In string context this is a binary string.
4514
In number context this is a longlong value.
4517
bool Item_float::eq(const Item *arg,
4518
bool binary_cmp __attribute__((__unused__))) const
4520
if (arg->basic_const_item() && arg->type() == type())
4523
We need to cast off const to call val_int(). This should be OK for
4526
Item *item= (Item*) arg;
4527
return item->val_real() == value;
4533
inline uint char_val(char X)
4535
return (uint) (X >= '0' && X <= '9' ? X-'0' :
4536
X >= 'A' && X <= 'Z' ? X-'A'+10 :
4541
Item_hex_string::Item_hex_string(const char *str, uint str_length)
4543
max_length=(str_length+1)/2;
4544
char *ptr=(char*) sql_alloc(max_length+1);
4547
str_value.set(ptr,max_length,&my_charset_bin);
4548
char *end=ptr+max_length;
4549
if (max_length*2 != str_length)
4550
*ptr++=char_val(*str++); // Not even, assume 0 prefix
4553
*ptr++= (char) (char_val(str[0])*16+char_val(str[1]));
4556
*ptr=0; // Keep purify happy
4557
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
4562
longlong Item_hex_string::val_int()
4564
// following assert is redundant, because fixed=1 assigned in constructor
4566
char *end=(char*) str_value.ptr()+str_value.length(),
4567
*ptr=end-min(str_value.length(),sizeof(longlong));
4570
for (; ptr != end ; ptr++)
4571
value=(value << 8)+ (ulonglong) (uchar) *ptr;
4572
return (longlong) value;
4576
my_decimal *Item_hex_string::val_decimal(my_decimal *decimal_value)
4578
// following assert is redundant, because fixed=1 assigned in constructor
4580
ulonglong value= (ulonglong)val_int();
4581
int2my_decimal(E_DEC_FATAL_ERROR, value, true, decimal_value);
4582
return (decimal_value);
4586
int Item_hex_string::save_in_field(Field *field,
4587
bool no_conversions __attribute__((__unused__)))
4589
field->set_notnull();
4590
if (field->result_type() == STRING_RESULT)
4591
return field->store(str_value.ptr(), str_value.length(),
4592
collation.collation);
4595
uint32 length= str_value.length();
4598
nr= field->flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX;
4601
nr= (ulonglong) val_int();
4602
if ((length == 8) && !(field->flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX))
4607
return field->store((longlong) nr, true); // Assume hex numbers are unsigned
4610
if (!field->store((longlong) nr, true))
4611
field->set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE,
4617
void Item_hex_string::print(String *str,
4618
enum_query_type query_type __attribute__((__unused__)))
4620
char *end= (char*) str_value.ptr() + str_value.length(),
4621
*ptr= end - min(str_value.length(), sizeof(longlong));
4623
for (; ptr != end ; ptr++)
4625
str->append(_dig_vec_lower[((uchar) *ptr) >> 4]);
4626
str->append(_dig_vec_lower[((uchar) *ptr) & 0x0F]);
4631
bool Item_hex_string::eq(const Item *arg, bool binary_cmp) const
4633
if (arg->basic_const_item() && arg->type() == type())
4636
return !stringcmp(&str_value, &arg->str_value);
4637
return !sortcmp(&str_value, &arg->str_value, collation.collation);
4643
Item *Item_hex_string::safe_charset_converter(CHARSET_INFO *tocs)
4646
String tmp, *str= val_str(&tmp);
4648
if (!(conv= new Item_string(str->ptr(), str->length(), tocs)))
4650
conv->str_value.copy();
4651
conv->str_value.mark_as_const();
4658
In string context this is a binary string.
4659
In number context this is a longlong value.
4662
Item_bin_string::Item_bin_string(const char *str, uint str_length)
4664
const char *end= str + str_length - 1;
4668
max_length= (str_length + 7) >> 3;
4669
char *ptr= (char*) sql_alloc(max_length + 1);
4672
str_value.set(ptr, max_length, &my_charset_bin);
4673
ptr+= max_length - 1;
4674
ptr[1]= 0; // Set end null for string
4675
for (; end >= str; end--)
4688
collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
4694
Pack data in buffer for sending.
4697
bool Item_null::send(Protocol *protocol,
4698
String *packet __attribute__((__unused__)))
4700
return protocol->store_null();
4704
This is only called from items that is not of type item_field.
4707
bool Item::send(Protocol *protocol, String *buffer)
1340
4709
bool result= false;
1341
4710
enum_field_types f_type;
1343
4712
switch ((f_type=field_type())) {
1344
case DRIZZLE_TYPE_DATE:
1345
case DRIZZLE_TYPE_NULL:
1346
case DRIZZLE_TYPE_ENUM:
1347
case DRIZZLE_TYPE_BLOB:
1348
case DRIZZLE_TYPE_VARCHAR:
1349
case DRIZZLE_TYPE_UUID:
1350
case DRIZZLE_TYPE_DECIMAL:
1353
if ((res=val_str(buffer)))
1354
result= client->store(res->ptr(),res->length());
1357
case DRIZZLE_TYPE_LONG:
1362
result= client->store((int32_t)nr);
1365
case DRIZZLE_TYPE_LONGLONG:
1372
result= client->store((uint64_t)nr);
1374
result= client->store((int64_t)nr);
1378
case DRIZZLE_TYPE_DOUBLE:
1380
double nr= val_real();
1382
result= client->store(nr, decimals, buffer);
1385
case DRIZZLE_TYPE_DATETIME:
1386
case DRIZZLE_TYPE_TIMESTAMP:
1389
get_date(&tm, TIME_FUZZY_DATE);
1391
result= client->store(&tm);
4714
case MYSQL_TYPE_NULL:
4715
case MYSQL_TYPE_ENUM:
4716
case MYSQL_TYPE_SET:
4717
case MYSQL_TYPE_BLOB:
4718
case MYSQL_TYPE_STRING:
4719
case MYSQL_TYPE_VAR_STRING:
4720
case MYSQL_TYPE_VARCHAR:
4721
case MYSQL_TYPE_NEWDECIMAL:
4724
if ((res=val_str(buffer)))
4725
result= protocol->store(res->ptr(),res->length(),res->charset());
4728
case MYSQL_TYPE_TINY:
4733
result= protocol->store_tiny(nr);
4736
case MYSQL_TYPE_SHORT:
4737
case MYSQL_TYPE_YEAR:
4742
result= protocol->store_short(nr);
4745
case MYSQL_TYPE_LONG:
4750
result= protocol->store_long(nr);
4753
case MYSQL_TYPE_LONGLONG:
4758
result= protocol->store_longlong(nr, unsigned_flag);
4761
case MYSQL_TYPE_FLOAT:
4764
nr= (float) val_real();
4766
result= protocol->store(nr, decimals, buffer);
4769
case MYSQL_TYPE_DOUBLE:
4771
double nr= val_real();
4773
result= protocol->store(nr, decimals, buffer);
4776
case MYSQL_TYPE_DATETIME:
4777
case MYSQL_TYPE_TIMESTAMP:
4780
get_date(&tm, TIME_FUZZY_DATE);
4783
if (f_type == MYSQL_TYPE_NEWDATE)
4784
return protocol->store_date(&tm);
4786
result= protocol->store(&tm);
4790
case MYSQL_TYPE_TIME:
4795
result= protocol->store_time(&tm);
1395
4799
if (null_value)
1396
result= client->store();
4800
result= protocol->store_null();
4805
bool Item_field::send(Protocol *protocol,
4806
String *buffer __attribute__((__unused__)))
4808
return protocol->store(result_field);
4812
void Item_field::update_null_value()
4815
need to set no_errors to prevent warnings about type conversion
4818
THD *thd= field->table->in_use;
4821
no_errors= thd->no_errors;
4823
Item::update_null_value();
4824
thd->no_errors= no_errors;
4829
Add the field to the select list and substitute it for the reference to
4833
Item_field::update_value_transformer()
4834
select_arg current select
4837
If the field doesn't belong to the table being inserted into then it is
4838
added to the select list, pointer to it is stored in the ref_pointer_array
4839
of the select and the field itself is substituted for the Item_ref object.
4840
This is done in order to get correct values from update fields that
4841
belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY
4846
ref if all conditions are met
4847
this field otherwise
4850
Item *Item_field::update_value_transformer(uchar *select_arg)
4852
SELECT_LEX *select= (SELECT_LEX*)select_arg;
4855
if (field->table != select->context.table_list->table &&
4856
type() != Item::TRIGGER_FIELD_ITEM)
4858
List<Item> *all_fields= &select->join->all_fields;
4859
Item **ref_pointer_array= select->ref_pointer_array;
4860
int el= all_fields->elements;
4863
ref_pointer_array[el]= (Item*)this;
4864
all_fields->push_front((Item*)this);
4865
ref= new Item_ref(&select->context, ref_pointer_array + el,
4866
table_name, field_name);
4873
void Item_field::print(String *str, enum_query_type query_type)
4875
if (field && field->table->const_table)
4877
char buff[MAX_FIELD_WIDTH];
4878
String tmp(buff,sizeof(buff),str->charset());
4879
field->val_str(&tmp);
4885
Item_ident::print(str, query_type);
4889
Item_ref::Item_ref(Name_resolution_context *context_arg,
4890
Item **item, const char *table_name_arg,
4891
const char *field_name_arg,
4892
bool alias_name_used_arg)
4893
:Item_ident(context_arg, NullS, table_name_arg, field_name_arg),
4894
result_field(0), ref(item)
4896
alias_name_used= alias_name_used_arg;
4898
This constructor used to create some internals references over fixed items
4900
if (ref && *ref && (*ref)->fixed)
4906
Resolve the name of a reference to a column reference.
4908
The method resolves the column reference represented by 'this' as a column
4909
present in one of: GROUP BY clause, SELECT clause, outer queries. It is
4910
used typically for columns in the HAVING clause which are not under
4911
aggregate functions.
4914
Item_ref::ref is 0 or points to a valid item.
4917
The name resolution algorithm used is (where [T_j] is an optional table
4918
name that qualifies the column name):
4921
resolve_extended([T_j].col_ref_i)
4923
Search for a column or derived column named col_ref_i [in table T_j]
4924
in the SELECT and GROUP clauses of Q.
4926
if such a column is NOT found AND // Lookup in outer queries.
4927
there are outer queries
4929
for each outer query Q_k beginning from the inner-most one
4931
Search for a column or derived column named col_ref_i
4932
[in table T_j] in the SELECT and GROUP clauses of Q_k.
4934
if such a column is not found AND
4935
- Q_k is not a group query AND
4936
- Q_k is not inside an aggregate function
4938
- Q_(k-1) is not in a HAVING or SELECT clause of Q_k
4940
search for a column or derived column named col_ref_i
4941
[in table T_j] in the FROM clause of Q_k;
4948
This procedure treats GROUP BY and SELECT clauses as one namespace for
4949
column references in HAVING. Notice that compared to
4950
Item_field::fix_fields, here we first search the SELECT and GROUP BY
4951
clauses, and then we search the FROM clause.
4953
@param[in] thd current thread
4954
@param[in,out] reference view column if this item was resolved to a
4958
Here we could first find the field anyway, and then test this
4959
condition, so that we can give a better error message -
4960
ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
4961
ER_BAD_FIELD_ERROR which we produce now.
4969
bool Item_ref::fix_fields(THD *thd, Item **reference)
4971
enum_parsing_place place= NO_MATTER;
4973
SELECT_LEX *current_sel= thd->lex->current_select;
4975
if (!ref || ref == not_found_item)
4977
if (!(ref= resolve_ref_in_select_and_group(thd, this,
4978
context->select_lex)))
4979
goto error; /* Some error occurred (e.g. ambiguous names). */
4981
if (ref == not_found_item) /* This reference was not resolved. */
4983
Name_resolution_context *last_checked_context= context;
4984
Name_resolution_context *outer_context= context->outer_context;
4990
/* The current reference cannot be resolved in this query. */
4991
my_error(ER_BAD_FIELD_ERROR,MYF(0),
4992
this->full_name(), current_thd->where);
4997
If there is an outer context (select), and it is not a derived table
4998
(which do not support the use of outer fields for now), try to
4999
resolve this reference in the outer select(s).
5001
We treat each subselect as a separate namespace, so that different
5002
subselects may contain columns with the same names. The subselects are
5003
searched starting from the innermost.
5005
from_field= (Field*) not_found_field;
5009
SELECT_LEX *select= outer_context->select_lex;
5010
Item_subselect *prev_subselect_item=
5011
last_checked_context->select_lex->master_unit()->item;
5012
last_checked_context= outer_context;
5014
/* Search in the SELECT and GROUP lists of the outer select. */
5015
if (outer_context->resolve_in_select_list)
5017
if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
5018
goto error; /* Some error occurred (e.g. ambiguous names). */
5019
if (ref != not_found_item)
5021
assert(*ref && (*ref)->fixed);
5022
prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
5023
prev_subselect_item->const_item_cache&= (*ref)->const_item();
5027
Set ref to 0 to ensure that we get an error in case we replaced
5028
this item with another item and still use this item in some
5029
other place of the parse tree.
5034
place= prev_subselect_item->parsing_place;
5036
Check table fields only if the subquery is used somewhere out of
5037
HAVING or the outer SELECT does not use grouping (i.e. tables are
5040
Here we could first find the field anyway, and then test this
5041
condition, so that we can give a better error message -
5042
ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
5043
ER_BAD_FIELD_ERROR which we produce now.
5045
if ((place != IN_HAVING ||
5046
(!select->with_sum_func &&
5047
select->group_list.elements == 0)))
5050
In case of view, find_field_in_tables() write pointer to view
5051
field expression to 'reference', i.e. it substitute that
5052
expression instead of this Item_ref
5054
from_field= find_field_in_tables(thd, this,
5056
first_name_resolution_table,
5058
last_name_resolution_table,
5060
IGNORE_EXCEPT_NON_UNIQUE,
5064
if (from_field == view_ref_found)
5066
Item::Type refer_type= (*reference)->type();
5067
prev_subselect_item->used_tables_cache|=
5068
(*reference)->used_tables();
5069
prev_subselect_item->const_item_cache&=
5070
(*reference)->const_item();
5071
assert((*reference)->type() == REF_ITEM);
5072
mark_as_dependent(thd, last_checked_context->select_lex,
5073
context->select_lex, this,
5074
((refer_type == REF_ITEM ||
5075
refer_type == FIELD_ITEM) ?
5076
(Item_ident*) (*reference) :
5079
view reference found, we substituted it instead of this
5084
if (from_field != not_found_field)
5086
if (cached_table && cached_table->select_lex &&
5087
outer_context->select_lex &&
5088
cached_table->select_lex != outer_context->select_lex)
5091
Due to cache, find_field_in_tables() can return field which
5092
doesn't belong to provided outer_context. In this case we have
5093
to find proper field context in order to fix field correcly.
5097
outer_context= outer_context->outer_context;
5098
select= outer_context->select_lex;
5099
prev_subselect_item=
5100
last_checked_context->select_lex->master_unit()->item;
5101
last_checked_context= outer_context;
5102
} while (outer_context && outer_context->select_lex &&
5103
cached_table->select_lex != outer_context->select_lex);
5105
prev_subselect_item->used_tables_cache|= from_field->table->map;
5106
prev_subselect_item->const_item_cache= 0;
5110
assert(from_field == not_found_field);
5112
/* Reference is not found => depend on outer (or just error). */
5113
prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
5114
prev_subselect_item->const_item_cache= 0;
5116
outer_context= outer_context->outer_context;
5117
} while (outer_context);
5119
assert(from_field != 0 && from_field != view_ref_found);
5120
if (from_field != not_found_field)
5123
if (!(fld= new Item_field(from_field)))
5125
thd->change_item_tree(reference, fld);
5126
mark_as_dependent(thd, last_checked_context->select_lex,
5127
thd->lex->current_select, this, fld);
5129
A reference is resolved to a nest level that's outer or the same as
5130
the nest level of the enclosing set function : adjust the value of
5131
max_arg_level for the function if it's needed.
5133
if (thd->lex->in_sum_func &&
5134
thd->lex->in_sum_func->nest_level >=
5135
last_checked_context->select_lex->nest_level)
5136
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5137
last_checked_context->select_lex->nest_level);
5142
/* The item was not a table field and not a reference */
5143
my_error(ER_BAD_FIELD_ERROR, MYF(0),
5144
this->full_name(), current_thd->where);
5147
/* Should be checked in resolve_ref_in_select_and_group(). */
5148
assert(*ref && (*ref)->fixed);
5149
mark_as_dependent(thd, last_checked_context->select_lex,
5150
context->select_lex, this, this);
5152
A reference is resolved to a nest level that's outer or the same as
5153
the nest level of the enclosing set function : adjust the value of
5154
max_arg_level for the function if it's needed.
5156
if (thd->lex->in_sum_func &&
5157
thd->lex->in_sum_func->nest_level >=
5158
last_checked_context->select_lex->nest_level)
5159
set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5160
last_checked_context->select_lex->nest_level);
5166
Check if this is an incorrect reference in a group function or forward
5167
reference. Do not issue an error if this is:
5168
1. outer reference (will be fixed later by the fix_inner_refs function);
5169
2. an unnamed reference inside an aggregate function.
5171
if (!((*ref)->type() == REF_ITEM &&
5172
((Item_ref *)(*ref))->ref_type() == OUTER_REF) &&
5173
(((*ref)->with_sum_func && name &&
5174
!(current_sel->linkage != GLOBAL_OPTIONS_TYPE &&
5175
current_sel->having_fix_field)) ||
5178
my_error(ER_ILLEGAL_REFERENCE, MYF(0),
5179
name, ((*ref)->with_sum_func?
5180
"reference to group function":
5181
"forward reference in item list"));
5187
if ((*ref)->check_cols(1))
5192
context->process_error(thd);
5197
void Item_ref::set_properties()
5199
max_length= (*ref)->max_length;
5200
maybe_null= (*ref)->maybe_null;
5201
decimals= (*ref)->decimals;
5202
collation.set((*ref)->collation);
5204
We have to remember if we refer to a sum function, to ensure that
5205
split_sum_func() doesn't try to change the reference.
5207
with_sum_func= (*ref)->with_sum_func;
5208
unsigned_flag= (*ref)->unsigned_flag;
5210
if (alias_name_used)
5212
if ((*ref)->type() == FIELD_ITEM)
5213
alias_name_used= ((Item_ident *) (*ref))->alias_name_used;
5215
alias_name_used= true; // it is not field, so it is was resolved by alias
5219
void Item_ref::cleanup()
5221
Item_ident::cleanup();
5227
void Item_ref::print(String *str, enum_query_type query_type)
5231
if ((*ref)->type() != Item::CACHE_ITEM && ref_type() != VIEW_REF &&
5232
!table_name && name && alias_name_used)
5234
THD *thd= current_thd;
5235
append_identifier(thd, str, name, (uint) strlen(name));
5238
(*ref)->print(str, query_type);
5241
Item_ident::print(str, query_type);
5245
bool Item_ref::send(Protocol *prot, String *tmp)
5248
return prot->store(result_field);
5249
return (*ref)->send(prot, tmp);
5253
double Item_ref::val_result()
5257
if ((null_value= result_field->is_null()))
5259
return result_field->val_real();
5265
longlong Item_ref::val_int_result()
5269
if ((null_value= result_field->is_null()))
5271
return result_field->val_int();
5277
String *Item_ref::str_result(String* str)
5281
if ((null_value= result_field->is_null()))
5283
str->set_charset(str_value.charset());
5284
return result_field->val_str(str, &str_value);
5286
return val_str(str);
5290
my_decimal *Item_ref::val_decimal_result(my_decimal *decimal_value)
5294
if ((null_value= result_field->is_null()))
5296
return result_field->val_decimal(decimal_value);
5298
return val_decimal(decimal_value);
5302
bool Item_ref::val_bool_result()
5306
if ((null_value= result_field->is_null()))
5308
switch (result_field->result_type()) {
5310
return result_field->val_int() != 0;
5311
case DECIMAL_RESULT:
5313
my_decimal decimal_value;
5314
my_decimal *val= result_field->val_decimal(&decimal_value);
5316
return !my_decimal_is_zero(val);
5321
return result_field->val_real() != 0.0;
5331
double Item_ref::val_real()
5334
double tmp=(*ref)->val_result();
5335
null_value=(*ref)->null_value;
5340
longlong Item_ref::val_int()
5343
longlong tmp=(*ref)->val_int_result();
5344
null_value=(*ref)->null_value;
5349
bool Item_ref::val_bool()
5352
bool tmp= (*ref)->val_bool_result();
5353
null_value= (*ref)->null_value;
5358
String *Item_ref::val_str(String* tmp)
5361
tmp=(*ref)->str_result(tmp);
5362
null_value=(*ref)->null_value;
5367
bool Item_ref::is_null()
5370
return (*ref)->is_null();
5374
bool Item_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
5376
return (null_value=(*ref)->get_date_result(ltime,fuzzydate));
5380
my_decimal *Item_ref::val_decimal(my_decimal *decimal_value)
5382
my_decimal *val= (*ref)->val_decimal_result(decimal_value);
5383
null_value= (*ref)->null_value;
5387
int Item_ref::save_in_field(Field *to, bool no_conversions)
5390
assert(!result_field);
5391
res= (*ref)->save_in_field(to, no_conversions);
5392
null_value= (*ref)->null_value;
5397
void Item_ref::save_org_in_field(Field *field)
5399
(*ref)->save_org_in_field(field);
5403
void Item_ref::make_field(Send_field *field)
5405
(*ref)->make_field(field);
5406
/* Non-zero in case of a view */
5408
field->col_name= name;
5410
field->table_name= table_name;
5412
field->db_name= db_name;
5416
Item *Item_ref::get_tmp_table_item(THD *thd)
5419
return (*ref)->get_tmp_table_item(thd);
5421
Item_field *item= new Item_field(result_field);
5424
item->table_name= table_name;
5425
item->db_name= db_name;
5431
void Item_ref_null_helper::print(String *str, enum_query_type query_type)
5433
str->append(STRING_WITH_LEN("<ref_null_helper>("));
5435
(*ref)->print(str, query_type);
5442
double Item_direct_ref::val_real()
5444
double tmp=(*ref)->val_real();
5445
null_value=(*ref)->null_value;
5450
longlong Item_direct_ref::val_int()
5452
longlong tmp=(*ref)->val_int();
5453
null_value=(*ref)->null_value;
5458
String *Item_direct_ref::val_str(String* tmp)
5460
tmp=(*ref)->val_str(tmp);
5461
null_value=(*ref)->null_value;
5466
my_decimal *Item_direct_ref::val_decimal(my_decimal *decimal_value)
5468
my_decimal *tmp= (*ref)->val_decimal(decimal_value);
5469
null_value=(*ref)->null_value;
5474
bool Item_direct_ref::val_bool()
5476
bool tmp= (*ref)->val_bool();
5477
null_value=(*ref)->null_value;
5482
bool Item_direct_ref::is_null()
5484
return (*ref)->is_null();
5488
bool Item_direct_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
5490
return (null_value=(*ref)->get_date(ltime,fuzzydate));
5495
Prepare referenced field then call usual Item_direct_ref::fix_fields .
5497
@param thd thread handler
5498
@param reference reference on reference where this item stored
5506
bool Item_direct_view_ref::fix_fields(THD *thd, Item **reference)
5508
/* view fild reference must be defined */
5510
/* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */
5511
if (!(*ref)->fixed &&
5512
((*ref)->fix_fields(thd, ref)))
5514
return Item_direct_ref::fix_fields(thd, reference);
5518
Prepare referenced outer field then call usual Item_direct_ref::fix_fields
5521
Item_outer_ref::fix_fields()
5523
reference reference on reference where this item stored
5530
bool Item_outer_ref::fix_fields(THD *thd, Item **reference)
5533
/* outer_ref->check_cols() will be made in Item_direct_ref::fix_fields */
5534
if ((*ref) && !(*ref)->fixed && ((*ref)->fix_fields(thd, reference)))
5536
err= Item_direct_ref::fix_fields(thd, reference);
5539
if ((*ref)->type() == Item::FIELD_ITEM)
5540
table_name= ((Item_field*)outer_ref)->table_name;
5544
void Item_outer_ref::fix_after_pullout(st_select_lex *new_parent, Item **ref)
5546
if (depended_from == new_parent)
5549
outer_ref->fix_after_pullout(new_parent, ref);
5553
void Item_ref::fix_after_pullout(st_select_lex *new_parent,
5554
Item **refptr __attribute__((__unused__)))
5556
if (depended_from == new_parent)
5558
(*ref)->fix_after_pullout(new_parent, ref);
5559
depended_from= NULL;
5564
Compare two view column references for equality.
5566
A view column reference is considered equal to another column
5567
reference if the second one is a view column and if both column
5568
references resolve to the same item. It is assumed that both
5569
items are of the same type.
5571
@param item item to compare with
5572
@param binary_cmp make binary comparison
5575
true Referenced item is equal to given item
5580
bool Item_direct_view_ref::eq(const Item *item,
5581
bool binary_cmp __attribute__((__unused__))) const
5583
if (item->type() == REF_ITEM)
5585
Item_ref *item_ref= (Item_ref*) item;
5586
if (item_ref->ref_type() == VIEW_REF)
5588
Item *item_ref_ref= *(item_ref->ref);
5589
return ((*ref)->real_item() == item_ref_ref->real_item());
5595
bool Item_default_value::eq(const Item *item, bool binary_cmp) const
5597
return item->type() == DEFAULT_VALUE_ITEM &&
5598
((Item_default_value *)item)->arg->eq(arg, binary_cmp);
5602
bool Item_default_value::fix_fields(THD *thd,
5603
Item **items __attribute__((__unused__)))
5606
Item_field *field_arg;
5615
if (!arg->fixed && arg->fix_fields(thd, &arg))
5619
real_arg= arg->real_item();
5620
if (real_arg->type() != FIELD_ITEM)
5622
my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->name);
5626
field_arg= (Item_field *)real_arg;
5627
if (field_arg->field->flags & NO_DEFAULT_VALUE_FLAG)
5629
my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), field_arg->field->field_name);
5632
if (!(def_field= (Field*) sql_alloc(field_arg->field->size_of())))
5634
memcpy(def_field, field_arg->field, field_arg->field->size_of());
5635
def_field->move_field_offset((my_ptrdiff_t)
5636
(def_field->table->s->default_values -
5637
def_field->table->record[0]));
5638
set_field(def_field);
5642
context->process_error(thd);
5647
void Item_default_value::print(String *str, enum_query_type query_type)
5651
str->append(STRING_WITH_LEN("default"));
5654
str->append(STRING_WITH_LEN("default("));
5655
arg->print(str, query_type);
5660
int Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
5664
if (field_arg->flags & NO_DEFAULT_VALUE_FLAG)
5666
if (field_arg->reset())
5668
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
5669
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
5674
push_warning_printf(field_arg->table->in_use,
5675
MYSQL_ERROR::WARN_LEVEL_WARN,
5676
ER_NO_DEFAULT_FOR_FIELD,
5677
ER(ER_NO_DEFAULT_FOR_FIELD),
5678
field_arg->field_name);
5682
field_arg->set_default();
5685
return Item_field::save_in_field(field_arg, no_conversions);
5690
This method like the walk method traverses the item tree, but at the
5691
same time it can replace some nodes in the tree.
5694
Item *Item_default_value::transform(Item_transformer transformer, uchar *args)
5696
Item *new_item= arg->transform(transformer, args);
5701
THD::change_item_tree() should be called only if the tree was
5702
really transformed, i.e. when a new item has been created.
5703
Otherwise we'll be allocating a lot of unnecessary memory for
5704
change records at each execution.
5706
if (arg != new_item)
5707
current_thd->change_item_tree(&arg, new_item);
5708
return (this->*transformer)(args);
5712
bool Item_insert_value::eq(const Item *item, bool binary_cmp) const
5714
return item->type() == INSERT_VALUE_ITEM &&
5715
((Item_default_value *)item)->arg->eq(arg, binary_cmp);
5719
bool Item_insert_value::fix_fields(THD *thd,
5720
Item **items __attribute__((__unused__)))
5723
/* We should only check that arg is in first table */
5727
TABLE_LIST *orig_next_table= context->last_name_resolution_table;
5728
context->last_name_resolution_table= context->first_name_resolution_table;
5729
res= arg->fix_fields(thd, &arg);
5730
context->last_name_resolution_table= orig_next_table;
5735
if (arg->type() == REF_ITEM)
5737
Item_ref *ref= (Item_ref *)arg;
5738
if (ref->ref[0]->type() != FIELD_ITEM)
5740
my_error(ER_BAD_FIELD_ERROR, MYF(0), "", "VALUES() function");
5746
According to our SQL grammar, VALUES() function can reference
5749
assert(arg->type() == FIELD_ITEM);
5751
Item_field *field_arg= (Item_field *)arg;
5753
if (field_arg->field->table->insert_values)
5755
Field *def_field= (Field*) sql_alloc(field_arg->field->size_of());
5758
memcpy(def_field, field_arg->field, field_arg->field->size_of());
5759
def_field->move_field_offset((my_ptrdiff_t)
5760
(def_field->table->insert_values -
5761
def_field->table->record[0]));
5762
set_field(def_field);
5766
Field *tmp_field= field_arg->field;
5767
/* charset doesn't matter here, it's to avoid sigsegv only */
5768
tmp_field= new Field_null(0, 0, Field::NONE, field_arg->field->field_name,
5772
tmp_field->init(field_arg->field->table);
5773
set_field(tmp_field);
5779
void Item_insert_value::print(String *str, enum_query_type query_type)
5781
str->append(STRING_WITH_LEN("values("));
5782
arg->print(str, query_type);
1401
5787
Item_result item_cmp_type(Item_result a,Item_result b)
1403
5789
if (a == STRING_RESULT && b == STRING_RESULT)
1404
5790
return STRING_RESULT;
1406
5791
if (a == INT_RESULT && b == INT_RESULT)
1407
5792
return INT_RESULT;
1408
5793
else if (a == ROW_RESULT || b == ROW_RESULT)
1409
5794
return ROW_RESULT;
1411
5795
if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
1412
5796
(b == INT_RESULT || b == DECIMAL_RESULT))
1413
5797
return DECIMAL_RESULT;
1415
5798
return REAL_RESULT;
1418
void resolve_const_item(Session *session, Item **ref, Item *comp_item)
5802
void resolve_const_item(THD *thd, Item **ref, Item *comp_item)
1420
5804
Item *item= *ref;
1421
5805
Item *new_item= NULL;
1422
5806
if (item->basic_const_item())
1423
return; /* Can't be better */
5807
return; // Can't be better
1424
5808
Item_result res_type=item_cmp_type(comp_item->result_type(),
1425
5809
item->result_type());
1426
char *name=item->name; /* Alloced by memory::sql_alloc */
5810
char *name=item->name; // Alloced by sql_alloc
1428
5812
switch (res_type) {
1429
5813
case STRING_RESULT:
5815
char buff[MAX_FIELD_WIDTH];
5816
String tmp(buff,sizeof(buff),&my_charset_bin),*result;
5817
result=item->val_str(&tmp);
5818
if (item->null_value)
5819
new_item= new Item_null(name);
1431
char buff[MAX_FIELD_WIDTH];
1432
String tmp(buff,sizeof(buff),&my_charset_bin),*result;
1433
result=item->val_str(&tmp);
1434
if (item->null_value)
1435
new_item= new Item_null(name);
1438
uint32_t length= result->length();
1439
char *tmp_str= memory::sql_strmake(result->ptr(), length);
1440
new_item= new Item_string(name, tmp_str, length, result->charset());
5822
uint length= result->length();
5823
char *tmp_str= sql_strmake(result->ptr(), length);
5824
new_item= new Item_string(name, tmp_str, length, result->charset());
1444
5828
case INT_RESULT:
1446
int64_t result=item->val_int();
1447
uint32_t length=item->max_length;
1448
bool null_value=item->null_value;
1449
new_item= (null_value ? (Item*) new Item_null(name) :
1450
(Item*) new Item_int(name, result, length));
5830
longlong result=item->val_int();
5831
uint length=item->max_length;
5832
bool null_value=item->null_value;
5833
new_item= (null_value ? (Item*) new Item_null(name) :
5834
(Item*) new Item_int(name, result, length));
1453
5837
case ROW_RESULT:
1454
if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
1457
Substitute constants only in Item_rows. Don't affect other Items
1458
with ROW_RESULT (eg Item_singlerow_subselect).
5838
if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
5841
Substitute constants only in Item_rows. Don't affect other Items
5842
with ROW_RESULT (eg Item_singlerow_subselect).
1460
For such Items more optimal is to detect if it is constant and replace
1461
it with Item_row. This would optimize queries like this:
1462
SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
1464
Item_row *item_row= (Item_row*) item;
1465
Item_row *comp_item_row= (Item_row*) comp_item;
1469
If item and comp_item are both Item_rows and have same number of cols
1470
then process items in Item_row one by one.
1471
We can't ignore NULL values here as this item may be used with <=>, in
1472
which case NULL's are significant.
1474
assert(item->result_type() == comp_item->result_type());
1475
assert(item_row->cols() == comp_item_row->cols());
1476
col= item_row->cols();
1478
resolve_const_item(session, item_row->addr(col),
1479
comp_item_row->element_index(col));
5844
For such Items more optimal is to detect if it is constant and replace
5845
it with Item_row. This would optimize queries like this:
5846
SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
5848
Item_row *item_row= (Item_row*) item;
5849
Item_row *comp_item_row= (Item_row*) comp_item;
5853
If item and comp_item are both Item_rows and have same number of cols
5854
then process items in Item_row one by one.
5855
We can't ignore NULL values here as this item may be used with <=>, in
5856
which case NULL's are significant.
5858
assert(item->result_type() == comp_item->result_type());
5859
assert(item_row->cols() == comp_item_row->cols());
5860
col= item_row->cols();
5862
resolve_const_item(thd, item_row->addr(col),
5863
comp_item_row->element_index(col));
1483
5867
case REAL_RESULT:
1484
{ // It must REAL_RESULT
1485
double result= item->val_real();
1486
uint32_t length=item->max_length,decimals=item->decimals;
1487
bool null_value=item->null_value;
1488
new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
1489
new Item_float(name, result, decimals, length));
5868
{ // It must REAL_RESULT
5869
double result= item->val_real();
5870
uint length=item->max_length,decimals=item->decimals;
5871
bool null_value=item->null_value;
5872
new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
5873
new Item_float(name, result, decimals, length));
1492
5876
case DECIMAL_RESULT:
1494
my_decimal decimal_value;
1495
my_decimal *result= item->val_decimal(&decimal_value);
1496
uint32_t length= item->max_length, decimals= item->decimals;
1497
bool null_value= item->null_value;
1498
new_item= (null_value ?
1499
(Item*) new Item_null(name) :
1500
(Item*) new Item_decimal(name, result, length, decimals));
5878
my_decimal decimal_value;
5879
my_decimal *result= item->val_decimal(&decimal_value);
5880
uint length= item->max_length, decimals= item->decimals;
5881
bool null_value= item->null_value;
5882
new_item= (null_value ?
5883
(Item*) new Item_null(name) :
5884
(Item*) new Item_decimal(name, result, length, decimals));
1506
session->change_item_tree(ref, new_item);
5891
thd->change_item_tree(ref, new_item);
5895
Return true if the value stored in the field is equal to the const
5898
We need to use this on the range optimizer because in some cases
5899
we can't store the value in the field without some precision/character loss.
1509
5902
bool field_is_equal_to_item(Field *field,Item *item)
1537
5928
field_val= field->val_decimal(&field_buf);
1538
5929
return !my_decimal_cmp(item_val, field_val);
1541
5931
double result= item->val_real();
1542
5932
if (item->null_value)
1545
5934
return result == field->val_real();
1548
void dummy_error_processor(Session *, void *)
1552
Create field for temporary table using type of given item.
1554
@param session Thread handler
1555
@param item Item to create a field for
1556
@param table Temporary table
1557
@param copy_func If set and item is a function, store copy of
1559
@param modify_item 1 if item->result_field should point to new
1560
item. This is relevent for how fill_record()
1562
If modify_item is 1 then fill_record() will
1563
update the record in the original table.
1564
If modify_item is 0 then fill_record() will
1565
update the temporary table
1566
@param convert_blob_length If >0 create a varstring(convert_blob_length)
1567
field instead of blob.
1574
static Field *create_tmp_field_from_item(Session *,
1575
Item *item, Table *table,
1576
Item ***copy_func, bool modify_item,
1577
uint32_t convert_blob_length)
5937
Item_cache* Item_cache::get_cache(const Item *item)
1579
bool maybe_null= item->maybe_null;
1580
Field *new_field= NULL;
1582
5939
switch (item->result_type()) {
1584
new_field= new Field_double(item->max_length, maybe_null,
1585
item->name, item->decimals, true);
1588
5940
case INT_RESULT:
1590
Select an integer type with the minimal fit precision.
1591
MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
1592
Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into
1593
Int32 -> make them field::Int64.
1595
if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
1596
new_field=new field::Int64(item->max_length, maybe_null,
1597
item->name, item->unsigned_flag);
1599
new_field=new field::Int32(item->max_length, maybe_null,
1600
item->name, item->unsigned_flag);
1604
assert(item->collation.collation);
1606
enum enum_field_types type;
1608
DATE/TIME fields have STRING_RESULT result type.
1609
To preserve type they needed to be handled separately.
1611
if ((type= item->field_type()) == DRIZZLE_TYPE_DATETIME ||
1612
type == DRIZZLE_TYPE_DATE ||
1613
type == DRIZZLE_TYPE_TIMESTAMP)
1615
new_field= item->tmp_table_field_from_field_type(table, 1);
1617
Make sure that the blob fits into a Field_varstring which has
1621
else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
1622
convert_blob_length <= Field_varstring::MAX_SIZE &&
1623
convert_blob_length)
1625
table->setVariableWidth();
1626
new_field= new Field_varstring(convert_blob_length, maybe_null,
1627
item->name, item->collation.collation);
1631
new_field= item->make_string_field(table);
1633
new_field->set_derivation(item->collation.derivation);
5941
return new Item_cache_int();
5943
return new Item_cache_real();
1636
5944
case DECIMAL_RESULT:
1638
uint8_t dec= item->decimals;
1639
uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
1640
uint32_t len= item->max_length;
1643
Trying to put too many digits overall in a DECIMAL(prec,dec)
1644
will always throw a warning. We must limit dec to
1645
DECIMAL_MAX_SCALE however to prevent an assert() later.
1650
signed int overflow;
1652
dec= min(dec, (uint8_t)DECIMAL_MAX_SCALE);
1655
If the value still overflows the field with the corrected dec,
1656
we'll throw out decimals rather than integers. This is still
1657
bad and of course throws a truncation warning.
1658
+1: for decimal point
1661
overflow= my_decimal_precision_to_length(intg + dec, dec,
1662
item->unsigned_flag) - len;
1665
dec= max(0, dec - overflow); // too long, discard fract
1667
len-= item->decimals - dec; // corrected value fits
1670
new_field= new Field_decimal(len,
1674
item->unsigned_flag);
5945
return new Item_cache_decimal();
5947
return new Item_cache_str(item);
1678
5948
case ROW_RESULT:
1679
// This case should never be choosen
5949
return new Item_cache_row();
5951
// should never be in real life
1685
new_field->init(table);
1687
if (copy_func && item->is_result_field())
1688
*((*copy_func)++) = item; // Save for copy_funcs
1691
item->set_result_field(new_field);
1693
if (item->type() == Item::NULL_ITEM)
1694
new_field->is_created_from_null_item= true;
1699
Field *create_tmp_field(Session *session,
1705
Field **default_field,
1708
bool make_copy_field,
1709
uint32_t convert_blob_length)
1712
Item::Type orig_type= type;
1715
if (type != Item::FIELD_ITEM &&
1716
item->real_item()->type() == Item::FIELD_ITEM)
1719
item= item->real_item();
1720
type= Item::FIELD_ITEM;
1724
case Item::SUM_FUNC_ITEM:
1726
Item_sum *item_sum=(Item_sum*) item;
1727
result= item_sum->create_tmp_field(group, table, convert_blob_length);
1729
my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
1732
case Item::FIELD_ITEM:
1733
case Item::DEFAULT_VALUE_ITEM:
1735
Item_field *field= (Item_field*) item;
1736
bool orig_modify= modify_item;
1737
if (orig_type == Item::REF_ITEM)
1740
If item have to be able to store NULLs but underlaid field can't do it,
1741
create_tmp_field_from_field() can't be used for tmp field creation.
1743
if (field->maybe_null && !field->field->maybe_null())
1745
result= create_tmp_field_from_item(session, item, table, NULL,
1746
modify_item, convert_blob_length);
1747
*from_field= field->field;
1748
if (result && modify_item)
1749
field->result_field= result;
1753
result= create_tmp_field_from_field(session, (*from_field= field->field),
1754
orig_item ? orig_item->name :
1757
modify_item ? field :
1759
convert_blob_length);
1761
if (orig_type == Item::REF_ITEM && orig_modify)
1762
((Item_ref*)orig_item)->set_result_field(result);
1763
if (field->field->eq_def(result))
1764
*default_field= field->field;
1768
case Item::FUNC_ITEM:
1770
case Item::COND_ITEM:
1771
case Item::FIELD_AVG_ITEM:
1772
case Item::FIELD_STD_ITEM:
1773
case Item::SUBSELECT_ITEM:
1774
/* The following can only happen with 'CREATE TABLE ... SELECT' */
1775
case Item::PROC_ITEM:
1776
case Item::INT_ITEM:
1777
case Item::REAL_ITEM:
1778
case Item::DECIMAL_ITEM:
1779
case Item::STRING_ITEM:
1780
case Item::REF_ITEM:
1781
case Item::NULL_ITEM:
1782
case Item::VARBIN_ITEM:
1783
if (make_copy_field)
1785
assert(((Item_result_field*)item)->result_field);
1786
*from_field= ((Item_result_field*)item)->result_field;
1788
return create_tmp_field_from_item(session, item, table,
1789
(make_copy_field ? 0 : copy_func),
1790
modify_item, convert_blob_length);
1791
case Item::TYPE_HOLDER:
1792
result= ((Item_type_holder *)item)->make_field_by_type(table);
1793
result->set_derivation(item->collation.derivation);
1795
default: // Dosen't have to be stored
1800
std::ostream& operator<<(std::ostream& output, const Item &item)
1803
output << item.name;
1805
output << drizzled::display::type(item.type());
1808
return output; // for multiple << operators.
1811
} /* namespace drizzled */
5958
void Item_cache::print(String *str, enum_query_type query_type)
5960
str->append(STRING_WITH_LEN("<cache>("));
5962
example->print(str, query_type);
5964
Item::print(str, query_type);
5969
void Item_cache_int::store(Item *item)
5971
value= item->val_int_result();
5972
null_value= item->null_value;
5973
unsigned_flag= item->unsigned_flag;
5977
void Item_cache_int::store(Item *item, longlong val_arg)
5980
null_value= item->null_value;
5981
unsigned_flag= item->unsigned_flag;
5985
String *Item_cache_int::val_str(String *str)
5988
str->set(value, default_charset());
5993
my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val)
5996
int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val);
6001
void Item_cache_real::store(Item *item)
6003
value= item->val_result();
6004
null_value= item->null_value;
6008
longlong Item_cache_real::val_int()
6011
return (longlong) rint(value);
6015
String* Item_cache_real::val_str(String *str)
6018
str->set_real(value, decimals, default_charset());
6023
my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val)
6026
double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
6031
void Item_cache_decimal::store(Item *item)
6033
my_decimal *val= item->val_decimal_result(&decimal_value);
6034
if (!(null_value= item->null_value) && val != &decimal_value)
6035
my_decimal2decimal(val, &decimal_value);
6038
double Item_cache_decimal::val_real()
6042
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res);
6046
longlong Item_cache_decimal::val_int()
6050
my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res);
6054
String* Item_cache_decimal::val_str(String *str)
6057
my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, false,
6059
my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str);
6063
my_decimal *Item_cache_decimal::val_decimal(my_decimal *val __attribute__((__unused__)))
6066
return &decimal_value;
6070
void Item_cache_str::store(Item *item)
6072
value_buff.set(buffer, sizeof(buffer), item->collation.collation);
6073
value= item->str_result(&value_buff);
6074
if ((null_value= item->null_value))
6076
else if (value != &value_buff)
6079
We copy string value to avoid changing value if 'item' is table field
6080
in queries like following (where t1.c is varchar):
6082
(select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'),
6083
(select c from t1 where a=t2.a)
6086
value_buff.copy(*value);
6091
double Item_cache_str::val_real()
6097
return my_strntod(value->charset(), (char*) value->ptr(),
6098
value->length(), &end_not_used, &err_not_used);
6103
longlong Item_cache_str::val_int()
6108
return my_strntoll(value->charset(), value->ptr(),
6109
value->length(), 10, (char**) 0, &err);
6114
my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val)
6118
string2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
6125
int Item_cache_str::save_in_field(Field *field, bool no_conversions)
6127
int res= Item_cache::save_in_field(field, no_conversions);
6128
return (is_varbinary && field->type() == MYSQL_TYPE_STRING &&
6129
value->length() < field->field_length) ? 1 : res;
6133
bool Item_cache_row::allocate(uint num)
6136
THD *thd= current_thd;
6138
(Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
6142
bool Item_cache_row::setup(Item * item)
6145
if (!values && allocate(item->cols()))
6147
for (uint i= 0; i < item_count; i++)
6149
Item *el= item->element_index(i);
6151
if (!(tmp= values[i]= Item_cache::get_cache(el)))
6159
void Item_cache_row::store(Item * item)
6162
item->bring_value();
6163
for (uint i= 0; i < item_count; i++)
6165
values[i]->store(item->element_index(i));
6166
null_value|= values[i]->null_value;
6171
void Item_cache_row::illegal_method_call(const char *method __attribute__((__unused__)))
6174
my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
6179
bool Item_cache_row::check_cols(uint c)
6181
if (c != item_count)
6183
my_error(ER_OPERAND_COLUMNS, MYF(0), c);
6190
bool Item_cache_row::null_inside()
6192
for (uint i= 0; i < item_count; i++)
6194
if (values[i]->cols() > 1)
6196
if (values[i]->null_inside())
6201
values[i]->update_null_value();
6202
if (values[i]->null_value)
6210
void Item_cache_row::bring_value()
6212
for (uint i= 0; i < item_count; i++)
6213
values[i]->bring_value();
6218
Item_type_holder::Item_type_holder(THD *thd, Item *item)
6219
:Item(thd, item), enum_set_typelib(0), fld_type(get_real_type(item))
6221
assert(item->fixed);
6222
maybe_null= item->maybe_null;
6223
collation.set(item->collation);
6224
get_full_info(item);
6225
/* fix variable decimals which always is NOT_FIXED_DEC */
6226
if (Field::result_merge_type(fld_type) == INT_RESULT)
6228
prev_decimal_int_part= item->decimal_int_part();
6233
Return expression type of Item_type_holder.
6236
Item_result (type of internal MySQL expression result)
6239
Item_result Item_type_holder::result_type() const
6241
return Field::result_merge_type(fld_type);
6246
Find real field type of item.
6249
type of field which should be created to store item value
6252
enum_field_types Item_type_holder::get_real_type(Item *item)
6254
switch(item->type())
6259
Item_fields::field_type ask Field_type() but sometimes field return
6260
a different type, like for enum/set, so we need to ask real type.
6262
Field *field= ((Item_field *) item)->field;
6263
enum_field_types type= field->real_type();
6264
if (field->is_created_from_null_item)
6265
return MYSQL_TYPE_NULL;
6266
/* work around about varchar type field detection */
6267
if (type == MYSQL_TYPE_STRING && field->type() == MYSQL_TYPE_VAR_STRING)
6268
return MYSQL_TYPE_VAR_STRING;
6274
Argument of aggregate function sometimes should be asked about field
6277
Item_sum *item_sum= (Item_sum *) item;
6278
if (item_sum->keep_field_type())
6279
return get_real_type(item_sum->args[0]);
6283
if (((Item_func *) item)->functype() == Item_func::GUSERVAR_FUNC)
6286
There are work around of problem with changing variable type on the
6287
fly and variable always report "string" as field type to get
6288
acceptable information for client in send_field, so we make field
6289
type from expression type.
6291
switch (item->result_type()) {
6293
return MYSQL_TYPE_VAR_STRING;
6295
return MYSQL_TYPE_LONGLONG;
6297
return MYSQL_TYPE_DOUBLE;
6298
case DECIMAL_RESULT:
6299
return MYSQL_TYPE_NEWDECIMAL;
6303
return MYSQL_TYPE_VAR_STRING;
6310
return item->field_type();
6314
Find field type which can carry current Item_type_holder type and
6317
@param thd thread handler
6318
@param item given item to join its parameters with this item ones
6321
true error - types are incompatible
6326
bool Item_type_holder::join_types(THD *thd __attribute__((__unused__)),
6329
uint max_length_orig= max_length;
6330
uint decimals_orig= decimals;
6331
fld_type= Field::field_type_merge(fld_type, get_real_type(item));
6333
int item_decimals= item->decimals;
6334
/* fix variable decimals which always is NOT_FIXED_DEC */
6335
if (Field::result_merge_type(fld_type) == INT_RESULT)
6337
decimals= max(decimals, item_decimals);
6339
if (Field::result_merge_type(fld_type) == DECIMAL_RESULT)
6341
decimals= min(max(decimals, item->decimals), DECIMAL_MAX_SCALE);
6342
int precision= min(max(prev_decimal_int_part, item->decimal_int_part())
6343
+ decimals, DECIMAL_MAX_PRECISION);
6344
unsigned_flag&= item->unsigned_flag;
6345
max_length= my_decimal_precision_to_length(precision, decimals,
6349
switch (Field::result_merge_type(fld_type))
6353
const char *old_cs, *old_derivation;
6354
uint32 old_max_chars= max_length / collation.collation->mbmaxlen;
6355
old_cs= collation.collation->name;
6356
old_derivation= collation.derivation_name();
6357
if (collation.aggregate(item->collation, MY_COLL_ALLOW_CONV))
6359
my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
6360
old_cs, old_derivation,
6361
item->collation.collation->name,
6362
item->collation.derivation_name(),
6367
To figure out max_length, we have to take into account possible
6368
expansion of the size of the values because of character set
6371
if (collation.collation != &my_charset_bin)
6373
max_length= max(old_max_chars * collation.collation->mbmaxlen,
6374
display_length(item) /
6375
item->collation.collation->mbmaxlen *
6376
collation.collation->mbmaxlen);
6379
set_if_bigger(max_length, display_length(item));
6384
if (decimals != NOT_FIXED_DEC)
6386
int delta1= max_length_orig - decimals_orig;
6387
int delta2= item->max_length - item->decimals;
6388
max_length= max(delta1, delta2) + decimals;
6389
if (fld_type == MYSQL_TYPE_FLOAT && max_length > FLT_DIG + 2)
6391
max_length= FLT_DIG + 6;
6392
decimals= NOT_FIXED_DEC;
6394
if (fld_type == MYSQL_TYPE_DOUBLE && max_length > DBL_DIG + 2)
6396
max_length= DBL_DIG + 7;
6397
decimals= NOT_FIXED_DEC;
6401
max_length= (fld_type == MYSQL_TYPE_FLOAT) ? FLT_DIG+6 : DBL_DIG+7;
6405
max_length= max(max_length, display_length(item));
6407
maybe_null|= item->maybe_null;
6408
get_full_info(item);
6410
/* Remember decimal integer part to be used in DECIMAL_RESULT handleng */
6411
prev_decimal_int_part= decimal_int_part();
6416
Calculate lenth for merging result for given Item type.
6418
@param item Item for length detection
6424
uint32 Item_type_holder::display_length(Item *item)
6426
if (item->type() == Item::FIELD_ITEM)
6427
return ((Item_field *)item)->max_disp_length();
6429
switch (item->field_type())
6431
case MYSQL_TYPE_TIMESTAMP:
6432
case MYSQL_TYPE_TIME:
6433
case MYSQL_TYPE_DATETIME:
6434
case MYSQL_TYPE_YEAR:
6435
case MYSQL_TYPE_NEWDATE:
6436
case MYSQL_TYPE_VARCHAR:
6437
case MYSQL_TYPE_NEWDECIMAL:
6438
case MYSQL_TYPE_ENUM:
6439
case MYSQL_TYPE_SET:
6440
case MYSQL_TYPE_BLOB:
6441
case MYSQL_TYPE_VAR_STRING:
6442
case MYSQL_TYPE_STRING:
6443
case MYSQL_TYPE_TINY:
6445
case MYSQL_TYPE_SHORT:
6447
case MYSQL_TYPE_LONG:
6448
return MY_INT32_NUM_DECIMAL_DIGITS;
6449
case MYSQL_TYPE_FLOAT:
6451
case MYSQL_TYPE_DOUBLE:
6453
case MYSQL_TYPE_NULL:
6455
case MYSQL_TYPE_LONGLONG:
6458
assert(0); // we should never go there
6465
Make temporary table field according collected information about type
6468
@param table temporary table for which we create fields
6474
Field *Item_type_holder::make_field_by_type(TABLE *table)
6477
The field functions defines a field to be not null if null_ptr is not 0
6479
uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
6483
case MYSQL_TYPE_ENUM:
6484
assert(enum_set_typelib);
6485
field= new Field_enum((uchar *) 0, max_length, null_ptr, 0,
6487
get_enum_pack_length(enum_set_typelib->count),
6488
enum_set_typelib, collation.collation);
6492
case MYSQL_TYPE_SET:
6493
assert(enum_set_typelib);
6494
field= new Field_set((uchar *) 0, max_length, null_ptr, 0,
6496
get_set_pack_length(enum_set_typelib->count),
6497
enum_set_typelib, collation.collation);
6501
case MYSQL_TYPE_NULL:
6502
return make_string_field(table);
6506
return tmp_table_field_from_field_type(table, 0);
6511
Get full information from Item about enum/set fields to be able to create
6514
@param item Item for information collection
6516
void Item_type_holder::get_full_info(Item *item)
6518
if (fld_type == MYSQL_TYPE_ENUM ||
6519
fld_type == MYSQL_TYPE_SET)
6521
if (item->type() == Item::SUM_FUNC_ITEM &&
6522
(((Item_sum*)item)->sum_func() == Item_sum::MAX_FUNC ||
6523
((Item_sum*)item)->sum_func() == Item_sum::MIN_FUNC))
6524
item = ((Item_sum*)item)->args[0];
6526
We can have enum/set type after merging only if we have one enum|set
6527
field (or MIN|MAX(enum|set field)) and number of NULL fields
6529
assert((enum_set_typelib &&
6530
get_real_type(item) == MYSQL_TYPE_NULL) ||
6531
(!enum_set_typelib &&
6532
item->type() == Item::FIELD_ITEM &&
6533
(get_real_type(item) == MYSQL_TYPE_ENUM ||
6534
get_real_type(item) == MYSQL_TYPE_SET) &&
6535
((Field_enum*)((Item_field *) item)->field)->typelib));
6536
if (!enum_set_typelib)
6538
enum_set_typelib= ((Field_enum*)((Item_field *) item)->field)->typelib;
6544
double Item_type_holder::val_real()
6546
assert(0); // should never be called
6551
longlong Item_type_holder::val_int()
6553
assert(0); // should never be called
6557
my_decimal *Item_type_holder::val_decimal(my_decimal *)
6559
assert(0); // should never be called
6563
String *Item_type_holder::val_str(String*)
6565
assert(0); // should never be called
6569
void Item_result_field::cleanup()
6577
Dummy error processor used by default by Name_resolution_context.
6583
void dummy_error_processor(THD *thd __attribute__((__unused__)),
6584
void *data __attribute__((__unused__)))
6588
Wrapper of hide_view_error call for Name_resolution_context error
6592
hide view underlying tables details in error messages
6595
/*****************************************************************************
6596
** Instantiate templates
6597
*****************************************************************************/
6599
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
6600
template class List<Item>;
6601
template class List_iterator<Item>;
6602
template class List_iterator_fast<Item>;
6603
template class List_iterator_fast<Item_field>;
6604
template class List<List_item>;