~ubuntu-branches/ubuntu/precise/mysql-5.1/precise

« back to all changes in this revision

Viewing changes to sql/item.cc

  • Committer: Bazaar Package Importer
  • Author(s): Norbert Tretkowski
  • Date: 2010-03-17 14:56:02 UTC
  • Revision ID: james.westby@ubuntu.com-20100317145602-x7e30l1b2sb5s6w6
Tags: upstream-5.1.45
ImportĀ upstreamĀ versionĀ 5.1.45

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
 
2
 
 
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.
 
6
 
 
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.
 
11
 
 
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 */
 
15
 
 
16
 
 
17
#ifdef USE_PRAGMA_IMPLEMENTATION
 
18
#pragma implementation                          // gcc: Class implementation
 
19
#endif
 
20
#include "mysql_priv.h"
 
21
#include <mysql.h>
 
22
#include <m_ctype.h>
 
23
#include "my_dir.h"
 
24
#include "sp_rcontext.h"
 
25
#include "sp_head.h"
 
26
#include "sql_trigger.h"
 
27
#include "sql_select.h"
 
28
 
 
29
const String my_null_string("NULL", 4, default_charset_info);
 
30
 
 
31
/****************************************************************************/
 
32
 
 
33
/* Hybrid_type_traits {_real} */
 
34
 
 
35
void Hybrid_type_traits::fix_length_and_dec(Item *item, Item *arg) const
 
36
{
 
37
  item->decimals= NOT_FIXED_DEC;
 
38
  item->max_length= item->float_length(arg->decimals);
 
39
}
 
40
 
 
41
static const Hybrid_type_traits real_traits_instance;
 
42
 
 
43
const Hybrid_type_traits *Hybrid_type_traits::instance()
 
44
{
 
45
  return &real_traits_instance;
 
46
}
 
47
 
 
48
 
 
49
my_decimal *
 
50
Hybrid_type_traits::val_decimal(Hybrid_type *val, my_decimal *to) const
 
51
{
 
52
  double2my_decimal(E_DEC_FATAL_ERROR, val->real, val->dec_buf);
 
53
  return val->dec_buf;
 
54
}
 
55
 
 
56
 
 
57
String *
 
58
Hybrid_type_traits::val_str(Hybrid_type *val, String *to, uint8 decimals) const
 
59
{
 
60
  to->set_real(val->real, decimals, &my_charset_bin);
 
61
  return to;
 
62
}
 
63
 
 
64
/* Hybrid_type_traits_decimal */
 
65
static const Hybrid_type_traits_decimal decimal_traits_instance;
 
66
 
 
67
const Hybrid_type_traits_decimal *Hybrid_type_traits_decimal::instance()
 
68
{
 
69
  return &decimal_traits_instance;
 
70
}
 
71
 
 
72
 
 
73
void
 
74
Hybrid_type_traits_decimal::fix_length_and_dec(Item *item, Item *arg) const
 
75
{
 
76
  item->decimals= arg->decimals;
 
77
  item->max_length= min(arg->max_length + DECIMAL_LONGLONG_DIGITS,
 
78
                        DECIMAL_MAX_STR_LENGTH);
 
79
}
 
80
 
 
81
 
 
82
void Hybrid_type_traits_decimal::set_zero(Hybrid_type *val) const
 
83
{
 
84
  my_decimal_set_zero(&val->dec_buf[0]);
 
85
  val->used_dec_buf_no= 0;
 
86
}
 
87
 
 
88
 
 
89
void Hybrid_type_traits_decimal::add(Hybrid_type *val, Field *f) const
 
90
{
 
91
  my_decimal_add(E_DEC_FATAL_ERROR,
 
92
                 &val->dec_buf[val->used_dec_buf_no ^ 1],
 
93
                 &val->dec_buf[val->used_dec_buf_no],
 
94
                 f->val_decimal(&val->dec_buf[2]));
 
95
  val->used_dec_buf_no^= 1;
 
96
}
 
97
 
 
98
 
 
99
/**
 
100
  @todo
 
101
  what is '4' for scale?
 
102
*/
 
103
void Hybrid_type_traits_decimal::div(Hybrid_type *val, ulonglong u) const
 
104
{
 
105
  int2my_decimal(E_DEC_FATAL_ERROR, u, TRUE, &val->dec_buf[2]);
 
106
  /* XXX: what is '4' for scale? */
 
107
  my_decimal_div(E_DEC_FATAL_ERROR,
 
108
                 &val->dec_buf[val->used_dec_buf_no ^ 1],
 
109
                 &val->dec_buf[val->used_dec_buf_no],
 
110
                 &val->dec_buf[2], 4);
 
111
  val->used_dec_buf_no^= 1;
 
112
}
 
113
 
 
114
 
 
115
longlong
 
116
Hybrid_type_traits_decimal::val_int(Hybrid_type *val, bool unsigned_flag) const
 
117
{
 
118
  longlong result;
 
119
  my_decimal2int(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
 
120
                 unsigned_flag, &result);
 
121
  return result;
 
122
}
 
123
 
 
124
 
 
125
double
 
126
Hybrid_type_traits_decimal::val_real(Hybrid_type *val) const
 
127
{
 
128
  my_decimal2double(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
 
129
                    &val->real);
 
130
  return val->real;
 
131
}
 
132
 
 
133
 
 
134
String *
 
135
Hybrid_type_traits_decimal::val_str(Hybrid_type *val, String *to,
 
136
                                    uint8 decimals) const
 
137
{
 
138
  my_decimal_round(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
 
139
                   decimals, FALSE, &val->dec_buf[2]);
 
140
  my_decimal2string(E_DEC_FATAL_ERROR, &val->dec_buf[2], 0, 0, 0, to);
 
141
  return to;
 
142
}
 
143
 
 
144
/* Hybrid_type_traits_integer */
 
145
static const Hybrid_type_traits_integer integer_traits_instance;
 
146
 
 
147
const Hybrid_type_traits_integer *Hybrid_type_traits_integer::instance()
 
148
{
 
149
  return &integer_traits_instance;
 
150
}
 
151
 
 
152
void
 
153
Hybrid_type_traits_integer::fix_length_and_dec(Item *item, Item *arg) const
 
154
{
 
155
  item->decimals= 0;
 
156
  item->max_length= MY_INT64_NUM_DECIMAL_DIGITS;
 
157
  item->unsigned_flag= 0;
 
158
}
 
159
 
 
160
/*****************************************************************************
 
161
** Item functions
 
162
*****************************************************************************/
 
163
 
 
164
/**
 
165
  Init all special items.
 
166
*/
 
167
 
 
168
void item_init(void)
 
169
{
 
170
  item_user_lock_init();
 
171
  uuid_short_init();
 
172
}
 
173
 
 
174
 
 
175
/**
 
176
  @todo
 
177
    Make this functions class dependent
 
178
*/
 
179
 
 
180
bool Item::val_bool()
 
181
{
 
182
  switch(result_type()) {
 
183
  case INT_RESULT:
 
184
    return val_int() != 0;
 
185
  case DECIMAL_RESULT:
 
186
  {
 
187
    my_decimal decimal_value;
 
188
    my_decimal *val= val_decimal(&decimal_value);
 
189
    if (val)
 
190
      return !my_decimal_is_zero(val);
 
191
    return 0;
 
192
  }
 
193
  case REAL_RESULT:
 
194
  case STRING_RESULT:
 
195
    return val_real() != 0.0;
 
196
  case ROW_RESULT:
 
197
  default:
 
198
    DBUG_ASSERT(0);
 
199
    return 0;                                   // Wrong (but safe)
 
200
  }
 
201
}
 
202
 
 
203
 
 
204
String *Item::val_string_from_real(String *str)
 
205
{
 
206
  double nr= val_real();
 
207
  if (null_value)
 
208
    return 0;                                   /* purecov: inspected */
 
209
  str->set_real(nr,decimals, &my_charset_bin);
 
210
  return str;
 
211
}
 
212
 
 
213
 
 
214
String *Item::val_string_from_int(String *str)
 
215
{
 
216
  longlong nr= val_int();
 
217
  if (null_value)
 
218
    return 0;
 
219
  str->set_int(nr, unsigned_flag, &my_charset_bin);
 
220
  return str;
 
221
}
 
222
 
 
223
 
 
224
String *Item::val_string_from_decimal(String *str)
 
225
{
 
226
  my_decimal dec_buf, *dec= val_decimal(&dec_buf);
 
227
  if (null_value)
 
228
    return 0;
 
229
  my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
 
230
  my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
 
231
  return str;
 
232
}
 
233
 
 
234
 
 
235
my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
 
236
{
 
237
  double nr= val_real();
 
238
  if (null_value)
 
239
    return 0;
 
240
  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
 
241
  return (decimal_value);
 
242
}
 
243
 
 
244
 
 
245
my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
 
246
{
 
247
  longlong nr= val_int();
 
248
  if (null_value)
 
249
    return 0;
 
250
  int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
 
251
  return decimal_value;
 
252
}
 
253
 
 
254
 
 
255
my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
 
256
{
 
257
  String *res;
 
258
  char *end_ptr;
 
259
  if (!(res= val_str(&str_value)))
 
260
    return 0;                                   // NULL or EOM
 
261
 
 
262
  end_ptr= (char*) res->ptr()+ res->length();
 
263
  if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
 
264
                     res->ptr(), res->length(), res->charset(),
 
265
                     decimal_value) & E_DEC_BAD_NUM)
 
266
  {
 
267
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
268
                        ER_TRUNCATED_WRONG_VALUE,
 
269
                        ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
 
270
                        str_value.c_ptr());
 
271
  }
 
272
  return decimal_value;
 
273
}
 
274
 
 
275
 
 
276
my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value)
 
277
{
 
278
  DBUG_ASSERT(fixed == 1);
 
279
  MYSQL_TIME ltime;
 
280
  if (get_date(&ltime, TIME_FUZZY_DATE))
 
281
  {
 
282
    my_decimal_set_zero(decimal_value);
 
283
    null_value= 1;                               // set NULL, stop processing
 
284
    return 0;
 
285
  }
 
286
  return date2my_decimal(&ltime, decimal_value);
 
287
}
 
288
 
 
289
 
 
290
my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value)
 
291
{
 
292
  DBUG_ASSERT(fixed == 1);
 
293
  MYSQL_TIME ltime;
 
294
  if (get_time(&ltime))
 
295
  {
 
296
    my_decimal_set_zero(decimal_value);
 
297
    return 0;
 
298
  }
 
299
  return date2my_decimal(&ltime, decimal_value);
 
300
}
 
301
 
 
302
 
 
303
double Item::val_real_from_decimal()
 
304
{
 
305
  /* Note that fix_fields may not be called for Item_avg_field items */
 
306
  double result;
 
307
  my_decimal value_buff, *dec_val= val_decimal(&value_buff);
 
308
  if (null_value)
 
309
    return 0.0;
 
310
  my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
 
311
  return result;
 
312
}
 
313
 
 
314
 
 
315
longlong Item::val_int_from_decimal()
 
316
{
 
317
  /* Note that fix_fields may not be called for Item_avg_field items */
 
318
  longlong result;
 
319
  my_decimal value, *dec_val= val_decimal(&value);
 
320
  if (null_value)
 
321
    return 0;
 
322
  my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result);
 
323
  return result;
 
324
}
 
325
 
 
326
int Item::save_time_in_field(Field *field)
 
327
{
 
328
  MYSQL_TIME ltime;
 
329
  if (get_time(&ltime))
 
330
    return set_field_to_null_with_conversions(field, 0);
 
331
  field->set_notnull();
 
332
  return field->store_time(&ltime, MYSQL_TIMESTAMP_TIME);
 
333
}
 
334
 
 
335
 
 
336
int Item::save_date_in_field(Field *field)
 
337
{
 
338
  MYSQL_TIME ltime;
 
339
  if (get_date(&ltime, TIME_FUZZY_DATE))
 
340
    return set_field_to_null_with_conversions(field, 0);
 
341
  field->set_notnull();
 
342
  return field->store_time(&ltime, MYSQL_TIMESTAMP_DATETIME);
 
343
}
 
344
 
 
345
 
 
346
/*
 
347
  Store the string value in field directly
 
348
 
 
349
  SYNOPSIS
 
350
    Item::save_str_value_in_field()
 
351
    field   a pointer to field where to store
 
352
    result  the pointer to the string value to be stored
 
353
 
 
354
  DESCRIPTION
 
355
    The method is used by Item_*::save_in_field implementations
 
356
    when we don't need to calculate the value to store
 
357
    See Item_string::save_in_field() implementation for example
 
358
 
 
359
  IMPLEMENTATION
 
360
    Check if the Item is null and stores the NULL or the
 
361
    result value in the field accordingly.
 
362
 
 
363
  RETURN
 
364
    Nonzero value if error
 
365
*/
 
366
 
 
367
int Item::save_str_value_in_field(Field *field, String *result)
 
368
{
 
369
  if (null_value)
 
370
    return set_field_to_null(field);
 
371
  field->set_notnull();
 
372
  return field->store(result->ptr(), result->length(),
 
373
                      collation.collation);
 
374
}
 
375
 
 
376
 
 
377
Item::Item():
 
378
  rsize(0), name(0), orig_name(0), name_length(0), fixed(0),
 
379
  is_autogenerated_name(TRUE),
 
380
  collation(&my_charset_bin, DERIVATION_COERCIBLE)
 
381
{
 
382
  marker= 0;
 
383
  maybe_null=null_value=with_sum_func=unsigned_flag=0;
 
384
  decimals= 0; max_length= 0;
 
385
  with_subselect= 0;
 
386
  cmp_context= (Item_result)-1;
 
387
 
 
388
  /* Put item in free list so that we can free all items at end */
 
389
  THD *thd= current_thd;
 
390
  next= thd->free_list;
 
391
  thd->free_list= this;
 
392
  /*
 
393
    Item constructor can be called during execution other then SQL_COM
 
394
    command => we should check thd->lex->current_select on zero (thd->lex
 
395
    can be uninitialised)
 
396
  */
 
397
  if (thd->lex->current_select)
 
398
  {
 
399
    enum_parsing_place place= 
 
400
      thd->lex->current_select->parsing_place;
 
401
    if (place == SELECT_LIST ||
 
402
        place == IN_HAVING)
 
403
      thd->lex->current_select->select_n_having_items++;
 
404
  }
 
405
}
 
406
 
 
407
/**
 
408
  Constructor used by Item_field, Item_ref & aggregate (sum)
 
409
  functions.
 
410
 
 
411
  Used for duplicating lists in processing queries with temporary
 
412
  tables.
 
413
*/
 
414
Item::Item(THD *thd, Item *item):
 
415
  rsize(0),
 
416
  str_value(item->str_value),
 
417
  name(item->name),
 
418
  orig_name(item->orig_name),
 
419
  max_length(item->max_length),
 
420
  name_length(item->name_length),
 
421
  marker(item->marker),
 
422
  decimals(item->decimals),
 
423
  maybe_null(item->maybe_null),
 
424
  null_value(item->null_value),
 
425
  unsigned_flag(item->unsigned_flag),
 
426
  with_sum_func(item->with_sum_func),
 
427
  fixed(item->fixed),
 
428
  is_autogenerated_name(item->is_autogenerated_name),
 
429
  collation(item->collation),
 
430
  with_subselect(item->with_subselect),
 
431
  cmp_context(item->cmp_context)
 
432
{
 
433
  next= thd->free_list;                         // Put in free list
 
434
  thd->free_list= this;
 
435
}
 
436
 
 
437
 
 
438
uint Item::decimal_precision() const
 
439
{
 
440
  Item_result restype= result_type();
 
441
 
 
442
  if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
 
443
  {
 
444
    uint prec= 
 
445
      my_decimal_length_to_precision(max_length, decimals, unsigned_flag);
 
446
    return min(prec, DECIMAL_MAX_PRECISION);
 
447
  }
 
448
  return min(max_length, DECIMAL_MAX_PRECISION);
 
449
}
 
450
 
 
451
 
 
452
void Item::print_item_w_name(String *str, enum_query_type query_type)
 
453
{
 
454
  print(str, query_type);
 
455
 
 
456
  if (name)
 
457
  {
 
458
    THD *thd= current_thd;
 
459
    str->append(STRING_WITH_LEN(" AS "));
 
460
    append_identifier(thd, str, name, (uint) strlen(name));
 
461
  }
 
462
}
 
463
 
 
464
 
 
465
void Item::cleanup()
 
466
{
 
467
  DBUG_ENTER("Item::cleanup");
 
468
  fixed=0;
 
469
  marker= 0;
 
470
  if (orig_name)
 
471
    name= orig_name;
 
472
  DBUG_VOID_RETURN;
 
473
}
 
474
 
 
475
 
 
476
/**
 
477
  cleanup() item if it is 'fixed'.
 
478
 
 
479
  @param arg   a dummy parameter, is not used here
 
480
*/
 
481
 
 
482
bool Item::cleanup_processor(uchar *arg)
 
483
{
 
484
  if (fixed)
 
485
    cleanup();
 
486
  return FALSE;
 
487
}
 
488
 
 
489
 
 
490
/**
 
491
  rename item (used for views, cleanup() return original name).
 
492
 
 
493
  @param new_name       new name of item;
 
494
*/
 
495
 
 
496
void Item::rename(char *new_name)
 
497
{
 
498
  /*
 
499
    we can compare pointers to names here, because if name was not changed,
 
500
    pointer will be same
 
501
  */
 
502
  if (!orig_name && new_name != name)
 
503
    orig_name= name;
 
504
  name= new_name;
 
505
}
 
506
 
 
507
 
 
508
/**
 
509
  Traverse item tree possibly transforming it (replacing items).
 
510
 
 
511
  This function is designed to ease transformation of Item trees.
 
512
  Re-execution note: every such transformation is registered for
 
513
  rollback by THD::change_item_tree() and is rolled back at the end
 
514
  of execution by THD::rollback_item_tree_changes().
 
515
 
 
516
  Therefore:
 
517
  - this function can not be used at prepared statement prepare
 
518
  (in particular, in fix_fields!), as only permanent
 
519
  transformation of Item trees are allowed at prepare.
 
520
  - the transformer function shall allocate new Items in execution
 
521
  memory root (thd->mem_root) and not anywhere else: allocated
 
522
  items will be gone in the end of execution.
 
523
 
 
524
  If you don't need to transform an item tree, but only traverse
 
525
  it, please use Item::walk() instead.
 
526
 
 
527
 
 
528
  @param transformer    functor that performs transformation of a subtree
 
529
  @param arg            opaque argument passed to the functor
 
530
 
 
531
  @return
 
532
    Returns pointer to the new subtree root.  THD::change_item_tree()
 
533
    should be called for it if transformation took place, i.e. if a
 
534
    pointer to newly allocated item is returned.
 
535
*/
 
536
 
 
537
Item* Item::transform(Item_transformer transformer, uchar *arg)
 
538
{
 
539
  DBUG_ASSERT(!current_thd->is_stmt_prepare());
 
540
 
 
541
  return (this->*transformer)(arg);
 
542
}
 
543
 
 
544
 
 
545
Item_ident::Item_ident(Name_resolution_context *context_arg,
 
546
                       const char *db_name_arg,const char *table_name_arg,
 
547
                       const char *field_name_arg)
 
548
  :orig_db_name(db_name_arg), orig_table_name(table_name_arg),
 
549
   orig_field_name(field_name_arg), context(context_arg),
 
550
   db_name(db_name_arg), table_name(table_name_arg),
 
551
   field_name(field_name_arg),
 
552
   alias_name_used(FALSE), cached_field_index(NO_CACHED_FIELD_INDEX),
 
553
   cached_table(0), depended_from(0)
 
554
{
 
555
  name = (char*) field_name_arg;
 
556
}
 
557
 
 
558
 
 
559
/**
 
560
  Constructor used by Item_field & Item_*_ref (see Item comment)
 
561
*/
 
562
 
 
563
Item_ident::Item_ident(THD *thd, Item_ident *item)
 
564
  :Item(thd, item),
 
565
   orig_db_name(item->orig_db_name),
 
566
   orig_table_name(item->orig_table_name), 
 
567
   orig_field_name(item->orig_field_name),
 
568
   context(item->context),
 
569
   db_name(item->db_name),
 
570
   table_name(item->table_name),
 
571
   field_name(item->field_name),
 
572
   alias_name_used(item->alias_name_used),
 
573
   cached_field_index(item->cached_field_index),
 
574
   cached_table(item->cached_table),
 
575
   depended_from(item->depended_from)
 
576
{}
 
577
 
 
578
void Item_ident::cleanup()
 
579
{
 
580
  DBUG_ENTER("Item_ident::cleanup");
 
581
#ifdef CANT_BE_USED_AS_MEMORY_IS_FREED
 
582
                       db_name ? db_name : "(null)",
 
583
                       orig_db_name ? orig_db_name : "(null)",
 
584
                       table_name ? table_name : "(null)",
 
585
                       orig_table_name ? orig_table_name : "(null)",
 
586
                       field_name ? field_name : "(null)",
 
587
                       orig_field_name ? orig_field_name : "(null)"));
 
588
#endif
 
589
  Item::cleanup();
 
590
  db_name= orig_db_name; 
 
591
  table_name= orig_table_name;
 
592
  field_name= orig_field_name;
 
593
  depended_from= 0;
 
594
  DBUG_VOID_RETURN;
 
595
}
 
596
 
 
597
bool Item_ident::remove_dependence_processor(uchar * arg)
 
598
{
 
599
  DBUG_ENTER("Item_ident::remove_dependence_processor");
 
600
  if (depended_from == (st_select_lex *) arg)
 
601
    depended_from= 0;
 
602
  context= &((st_select_lex *) arg)->context;
 
603
  DBUG_RETURN(0);
 
604
}
 
605
 
 
606
 
 
607
/**
 
608
  Store the pointer to this item field into a list if not already there.
 
609
 
 
610
  The method is used by Item::walk to collect all unique Item_field objects
 
611
  from a tree of Items into a set of items represented as a list.
 
612
 
 
613
  Item_cond::walk() and Item_func::walk() stop the evaluation of the
 
614
  processor function for its arguments once the processor returns
 
615
  true.Therefore in order to force this method being called for all item
 
616
  arguments in a condition the method must return false.
 
617
 
 
618
  @param arg  pointer to a List<Item_field>
 
619
 
 
620
  @return
 
621
    FALSE to force the evaluation of collect_item_field_processor
 
622
    for the subsequent items.
 
623
*/
 
624
 
 
625
bool Item_field::collect_item_field_processor(uchar *arg)
 
626
{
 
627
  DBUG_ENTER("Item_field::collect_item_field_processor");
 
628
  DBUG_PRINT("info", ("%s", field->field_name ? field->field_name : "noname"));
 
629
  List<Item_field> *item_list= (List<Item_field>*) arg;
 
630
  List_iterator<Item_field> item_list_it(*item_list);
 
631
  Item_field *curr_item;
 
632
  while ((curr_item= item_list_it++))
 
633
  {
 
634
    if (curr_item->eq(this, 1))
 
635
      DBUG_RETURN(FALSE); /* Already in the set. */
 
636
  }
 
637
  item_list->push_back(this);
 
638
  DBUG_RETURN(FALSE);
 
639
}
 
640
 
 
641
 
 
642
/**
 
643
  Check if an Item_field references some field from a list of fields.
 
644
 
 
645
  Check whether the Item_field represented by 'this' references any
 
646
  of the fields in the keyparts passed via 'arg'. Used with the
 
647
  method Item::walk() to test whether any keypart in a sequence of
 
648
  keyparts is referenced in an expression.
 
649
 
 
650
  @param arg   Field being compared, arg must be of type Field
 
651
 
 
652
  @retval
 
653
    TRUE  if 'this' references the field 'arg'
 
654
  @retval
 
655
    FALSE otherwise
 
656
*/
 
657
 
 
658
bool Item_field::find_item_in_field_list_processor(uchar *arg)
 
659
{
 
660
  KEY_PART_INFO *first_non_group_part= *((KEY_PART_INFO **) arg);
 
661
  KEY_PART_INFO *last_part= *(((KEY_PART_INFO **) arg) + 1);
 
662
  KEY_PART_INFO *cur_part;
 
663
 
 
664
  for (cur_part= first_non_group_part; cur_part != last_part; cur_part++)
 
665
  {
 
666
    if (field->eq(cur_part->field))
 
667
      return TRUE;
 
668
  }
 
669
  return FALSE;
 
670
}
 
671
 
 
672
 
 
673
/*
 
674
  Mark field in read_map
 
675
 
 
676
  NOTES
 
677
    This is used by filesort to register used fields in a a temporary
 
678
    column read set or to register used fields in a view
 
679
*/
 
680
 
 
681
bool Item_field::register_field_in_read_map(uchar *arg)
 
682
{
 
683
  TABLE *table= (TABLE *) arg;
 
684
  if (field->table == table || !table)
 
685
    bitmap_set_bit(field->table->read_set, field->field_index);
 
686
  return 0;
 
687
}
 
688
 
 
689
 
 
690
bool Item::check_cols(uint c)
 
691
{
 
692
  if (c != 1)
 
693
  {
 
694
    my_error(ER_OPERAND_COLUMNS, MYF(0), c);
 
695
    return 1;
 
696
  }
 
697
  return 0;
 
698
}
 
699
 
 
700
 
 
701
void Item::set_name(const char *str, uint length, CHARSET_INFO *cs)
 
702
{
 
703
  if (!length)
 
704
  {
 
705
    /* Empty string, used by AS or internal function like last_insert_id() */
 
706
    name= (char*) str;
 
707
    name_length= 0;
 
708
    return;
 
709
  }
 
710
  if (cs->ctype)
 
711
  {
 
712
    uint orig_len= length;
 
713
    /*
 
714
      This will probably need a better implementation in the future:
 
715
      a function in CHARSET_INFO structure.
 
716
    */
 
717
    while (length && !my_isgraph(cs,*str))
 
718
    {                                           // Fix problem with yacc
 
719
      length--;
 
720
      str++;
 
721
    }
 
722
    if (orig_len != length && !is_autogenerated_name)
 
723
    {
 
724
      if (length == 0)
 
725
        push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
726
                            ER_NAME_BECOMES_EMPTY, ER(ER_NAME_BECOMES_EMPTY),
 
727
                            str + length - orig_len);
 
728
      else
 
729
        push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
730
                            ER_REMOVED_SPACES, ER(ER_REMOVED_SPACES),
 
731
                            str + length - orig_len);
 
732
    }
 
733
  }
 
734
  if (!my_charset_same(cs, system_charset_info))
 
735
  {
 
736
    size_t res_length;
 
737
    name= sql_strmake_with_convert(str, name_length= length, cs,
 
738
                                   MAX_ALIAS_NAME, system_charset_info,
 
739
                                   &res_length);
 
740
  }
 
741
  else
 
742
    name= sql_strmake(str, (name_length= min(length,MAX_ALIAS_NAME)));
 
743
}
 
744
 
 
745
 
 
746
/**
 
747
  @details
 
748
  This function is called when:
 
749
  - Comparing items in the WHERE clause (when doing where optimization)
 
750
  - When trying to find an ORDER BY/GROUP BY item in the SELECT part
 
751
*/
 
752
 
 
753
bool Item::eq(const Item *item, bool binary_cmp) const
 
754
{
 
755
  /*
 
756
    Note, that this is never TRUE if item is a Item_param:
 
757
    for all basic constants we have special checks, and Item_param's
 
758
    type() can be only among basic constant types.
 
759
  */
 
760
  return type() == item->type() && name && item->name &&
 
761
    !my_strcasecmp(system_charset_info,name,item->name);
 
762
}
 
763
 
 
764
 
 
765
Item *Item::safe_charset_converter(CHARSET_INFO *tocs)
 
766
{
 
767
  Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1);
 
768
  return conv->safe ? conv : NULL;
 
769
}
 
770
 
 
771
 
 
772
/**
 
773
  @details
 
774
  Created mostly for mysql_prepare_table(). Important
 
775
  when a string ENUM/SET column is described with a numeric default value:
 
776
 
 
777
  CREATE TABLE t1(a SET('a') DEFAULT 1);
 
778
 
 
779
  We cannot use generic Item::safe_charset_converter(), because
 
780
  the latter returns a non-fixed Item, so val_str() crashes afterwards.
 
781
  Override Item_num method, to return a fixed item.
 
782
*/
 
783
Item *Item_num::safe_charset_converter(CHARSET_INFO *tocs)
 
784
{
 
785
  Item_string *conv;
 
786
  char buf[64];
 
787
  String *s, tmp(buf, sizeof(buf), &my_charset_bin);
 
788
  s= val_str(&tmp);
 
789
  if ((conv= new Item_string(s->ptr(), s->length(), s->charset())))
 
790
  {
 
791
    conv->str_value.copy();
 
792
    conv->str_value.mark_as_const();
 
793
  }
 
794
  return conv;
 
795
}
 
796
 
 
797
 
 
798
Item *Item_static_float_func::safe_charset_converter(CHARSET_INFO *tocs)
 
799
{
 
800
  Item_string *conv;
 
801
  char buf[64];
 
802
  String *s, tmp(buf, sizeof(buf), &my_charset_bin);
 
803
  s= val_str(&tmp);
 
804
  if ((conv= new Item_static_string_func(func_name, s->ptr(), s->length(),
 
805
                                         s->charset())))
 
806
  {
 
807
    conv->str_value.copy();
 
808
    conv->str_value.mark_as_const();
 
809
  }
 
810
  return conv;
 
811
}
 
812
 
 
813
 
 
814
Item *Item_string::safe_charset_converter(CHARSET_INFO *tocs)
 
815
{
 
816
  Item_string *conv;
 
817
  uint conv_errors;
 
818
  char *ptr;
 
819
  String tmp, cstr, *ostr= val_str(&tmp);
 
820
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
 
821
  if (conv_errors || !(conv= new Item_string(cstr.ptr(), cstr.length(),
 
822
                                             cstr.charset(),
 
823
                                             collation.derivation)))
 
824
  {
 
825
    /*
 
826
      Safe conversion is not possible (or EOM).
 
827
      We could not convert a string into the requested character set
 
828
      without data loss. The target charset does not cover all the
 
829
      characters from the string. Operation cannot be done correctly.
 
830
    */
 
831
    return NULL;
 
832
  }
 
833
  if (!(ptr= current_thd->strmake(cstr.ptr(), cstr.length())))
 
834
    return NULL;
 
835
  conv->str_value.set(ptr, cstr.length(), cstr.charset());
 
836
  /* Ensure that no one is going to change the result string */
 
837
  conv->str_value.mark_as_const();
 
838
  return conv;
 
839
}
 
840
 
 
841
 
 
842
Item *Item_param::safe_charset_converter(CHARSET_INFO *tocs)
 
843
{
 
844
  if (const_item())
 
845
  {
 
846
    uint cnv_errors;
 
847
    String *ostr= val_str(&cnvstr);
 
848
    cnvitem->str_value.copy(ostr->ptr(), ostr->length(),
 
849
                            ostr->charset(), tocs, &cnv_errors);
 
850
    if (cnv_errors)
 
851
       return NULL;
 
852
    cnvitem->str_value.mark_as_const();
 
853
    cnvitem->max_length= cnvitem->str_value.numchars() * tocs->mbmaxlen;
 
854
    return cnvitem;
 
855
  }
 
856
  return NULL;
 
857
}
 
858
 
 
859
 
 
860
Item *Item_static_string_func::safe_charset_converter(CHARSET_INFO *tocs)
 
861
{
 
862
  Item_string *conv;
 
863
  uint conv_errors;
 
864
  String tmp, cstr, *ostr= val_str(&tmp);
 
865
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
 
866
  if (conv_errors ||
 
867
      !(conv= new Item_static_string_func(func_name,
 
868
                                          cstr.ptr(), cstr.length(),
 
869
                                          cstr.charset(),
 
870
                                          collation.derivation)))
 
871
  {
 
872
    /*
 
873
      Safe conversion is not possible (or EOM).
 
874
      We could not convert a string into the requested character set
 
875
      without data loss. The target charset does not cover all the
 
876
      characters from the string. Operation cannot be done correctly.
 
877
    */
 
878
    return NULL;
 
879
  }
 
880
  conv->str_value.copy();
 
881
  /* Ensure that no one is going to change the result string */
 
882
  conv->str_value.mark_as_const();
 
883
  return conv;
 
884
}
 
885
 
 
886
 
 
887
bool Item_string::eq(const Item *item, bool binary_cmp) const
 
888
{
 
889
  if (type() == item->type() && item->basic_const_item())
 
890
  {
 
891
    if (binary_cmp)
 
892
      return !stringcmp(&str_value, &item->str_value);
 
893
    return (collation.collation == item->collation.collation &&
 
894
            !sortcmp(&str_value, &item->str_value, collation.collation));
 
895
  }
 
896
  return 0;
 
897
}
 
898
 
 
899
 
 
900
/**
 
901
  Get the value of the function as a MYSQL_TIME structure.
 
902
  As a extra convenience the time structure is reset on error!
 
903
*/
 
904
 
 
905
bool Item::get_date(MYSQL_TIME *ltime,uint fuzzydate)
 
906
{
 
907
  if (result_type() == STRING_RESULT)
 
908
  {
 
909
    char buff[40];
 
910
    String tmp(buff,sizeof(buff), &my_charset_bin),*res;
 
911
    if (!(res=val_str(&tmp)) ||
 
912
        str_to_datetime_with_warn(res->ptr(), res->length(),
 
913
                                  ltime, fuzzydate) <= MYSQL_TIMESTAMP_ERROR)
 
914
      goto err;
 
915
  }
 
916
  else
 
917
  {
 
918
    longlong value= val_int();
 
919
    int was_cut;
 
920
    if (number_to_datetime(value, ltime, fuzzydate, &was_cut) == LL(-1))
 
921
    {
 
922
      char buff[22], *end;
 
923
      end= longlong10_to_str(value, buff, -10);
 
924
      make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
925
                                   buff, (int) (end-buff), MYSQL_TIMESTAMP_NONE,
 
926
                                   NullS);
 
927
      goto err;
 
928
    }
 
929
  }
 
930
  return 0;
 
931
 
 
932
err:
 
933
  bzero((char*) ltime,sizeof(*ltime));
 
934
  return 1;
 
935
}
 
936
 
 
937
/**
 
938
  Get time of first argument.\
 
939
 
 
940
  As a extra convenience the time structure is reset on error!
 
941
*/
 
942
 
 
943
bool Item::get_time(MYSQL_TIME *ltime)
 
944
{
 
945
  char buff[40];
 
946
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
 
947
  if (!(res=val_str(&tmp)) ||
 
948
      str_to_time_with_warn(res->ptr(), res->length(), ltime))
 
949
  {
 
950
    bzero((char*) ltime,sizeof(*ltime));
 
951
    return 1;
 
952
  }
 
953
  return 0;
 
954
}
 
955
 
 
956
CHARSET_INFO *Item::default_charset()
 
957
{
 
958
  return current_thd->variables.collation_connection;
 
959
}
 
960
 
 
961
 
 
962
/*
 
963
  Save value in field, but don't give any warnings
 
964
 
 
965
  NOTES
 
966
   This is used to temporary store and retrieve a value in a column,
 
967
   for example in opt_range to adjust the key value to fit the column.
 
968
*/
 
969
 
 
970
int Item::save_in_field_no_warnings(Field *field, bool no_conversions)
 
971
{
 
972
  int res;
 
973
  TABLE *table= field->table;
 
974
  THD *thd= table->in_use;
 
975
  enum_check_fields tmp= thd->count_cuted_fields;
 
976
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
 
977
  ulong sql_mode= thd->variables.sql_mode;
 
978
  thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
 
979
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
980
  res= save_in_field(field, no_conversions);
 
981
  thd->count_cuted_fields= tmp;
 
982
  dbug_tmp_restore_column_map(table->write_set, old_map);
 
983
  thd->variables.sql_mode= sql_mode;
 
984
  return res;
 
985
}
 
986
 
 
987
 
 
988
/*****************************************************************************
 
989
  Item_sp_variable methods
 
990
*****************************************************************************/
 
991
 
 
992
Item_sp_variable::Item_sp_variable(char *sp_var_name_str,
 
993
                                   uint sp_var_name_length)
 
994
  :m_thd(0)
 
995
#ifndef DBUG_OFF
 
996
   , m_sp(0)
 
997
#endif
 
998
{
 
999
  m_name.str= sp_var_name_str;
 
1000
  m_name.length= sp_var_name_length;
 
1001
}
 
1002
 
 
1003
 
 
1004
bool Item_sp_variable::fix_fields(THD *thd, Item **)
 
1005
{
 
1006
  Item *it;
 
1007
 
 
1008
  m_thd= thd; /* NOTE: this must be set before any this_xxx() */
 
1009
  it= this_item();
 
1010
 
 
1011
  DBUG_ASSERT(it->fixed);
 
1012
 
 
1013
  max_length= it->max_length;
 
1014
  decimals= it->decimals;
 
1015
  unsigned_flag= it->unsigned_flag;
 
1016
  fixed= 1;
 
1017
  collation.set(it->collation.collation, it->collation.derivation);
 
1018
 
 
1019
  return FALSE;
 
1020
}
 
1021
 
 
1022
 
 
1023
double Item_sp_variable::val_real()
 
1024
{
 
1025
  DBUG_ASSERT(fixed);
 
1026
  Item *it= this_item();
 
1027
  double ret= it->val_real();
 
1028
  null_value= it->null_value;
 
1029
  return ret;
 
1030
}
 
1031
 
 
1032
 
 
1033
longlong Item_sp_variable::val_int()
 
1034
{
 
1035
  DBUG_ASSERT(fixed);
 
1036
  Item *it= this_item();
 
1037
  longlong ret= it->val_int();
 
1038
  null_value= it->null_value;
 
1039
  return ret;
 
1040
}
 
1041
 
 
1042
 
 
1043
String *Item_sp_variable::val_str(String *sp)
 
1044
{
 
1045
  DBUG_ASSERT(fixed);
 
1046
  Item *it= this_item();
 
1047
  String *res= it->val_str(sp);
 
1048
 
 
1049
  null_value= it->null_value;
 
1050
 
 
1051
  if (!res)
 
1052
    return NULL;
 
1053
 
 
1054
  /*
 
1055
    This way we mark returned value of val_str as const,
 
1056
    so that various functions (e.g. CONCAT) won't try to
 
1057
    modify the value of the Item. Analogous mechanism is
 
1058
    implemented for Item_param.
 
1059
    Without this trick Item_splocal could be changed as a
 
1060
    side-effect of expression computation. Here is an example
 
1061
    of what happens without it: suppose x is varchar local
 
1062
    variable in a SP with initial value 'ab' Then
 
1063
      select concat(x,'c');
 
1064
    would change x's value to 'abc', as Item_func_concat::val_str()
 
1065
    would use x's internal buffer to compute the result.
 
1066
    This is intended behaviour of Item_func_concat. Comments to
 
1067
    Item_param class contain some more details on the topic.
 
1068
  */
 
1069
 
 
1070
  if (res != &str_value)
 
1071
    str_value.set(res->ptr(), res->length(), res->charset());
 
1072
  else
 
1073
    res->mark_as_const();
 
1074
 
 
1075
  return &str_value;
 
1076
}
 
1077
 
 
1078
 
 
1079
my_decimal *Item_sp_variable::val_decimal(my_decimal *decimal_value)
 
1080
{
 
1081
  DBUG_ASSERT(fixed);
 
1082
  Item *it= this_item();
 
1083
  my_decimal *val= it->val_decimal(decimal_value);
 
1084
  null_value= it->null_value;
 
1085
  return val;
 
1086
}
 
1087
 
 
1088
 
 
1089
bool Item_sp_variable::is_null()
 
1090
{
 
1091
  return this_item()->is_null();
 
1092
}
 
1093
 
 
1094
 
 
1095
/*****************************************************************************
 
1096
  Item_splocal methods
 
1097
*****************************************************************************/
 
1098
 
 
1099
Item_splocal::Item_splocal(const LEX_STRING &sp_var_name,
 
1100
                           uint sp_var_idx,
 
1101
                           enum_field_types sp_var_type,
 
1102
                           uint pos_in_q, uint len_in_q)
 
1103
  :Item_sp_variable(sp_var_name.str, sp_var_name.length),
 
1104
   m_var_idx(sp_var_idx), pos_in_query(pos_in_q), len_in_query(len_in_q)
 
1105
{
 
1106
  maybe_null= TRUE;
 
1107
 
 
1108
  m_type= sp_map_item_type(sp_var_type);
 
1109
  m_field_type= sp_var_type;
 
1110
  m_result_type= sp_map_result_type(sp_var_type);
 
1111
}
 
1112
 
 
1113
 
 
1114
Item *
 
1115
Item_splocal::this_item()
 
1116
{
 
1117
  DBUG_ASSERT(m_sp == m_thd->spcont->sp);
 
1118
 
 
1119
  return m_thd->spcont->get_item(m_var_idx);
 
1120
}
 
1121
 
 
1122
const Item *
 
1123
Item_splocal::this_item() const
 
1124
{
 
1125
  DBUG_ASSERT(m_sp == m_thd->spcont->sp);
 
1126
 
 
1127
  return m_thd->spcont->get_item(m_var_idx);
 
1128
}
 
1129
 
 
1130
 
 
1131
Item **
 
1132
Item_splocal::this_item_addr(THD *thd, Item **)
 
1133
{
 
1134
  DBUG_ASSERT(m_sp == thd->spcont->sp);
 
1135
 
 
1136
  return thd->spcont->get_item_addr(m_var_idx);
 
1137
}
 
1138
 
 
1139
 
 
1140
void Item_splocal::print(String *str, enum_query_type)
 
1141
{
 
1142
  str->reserve(m_name.length+8);
 
1143
  str->append(m_name.str, m_name.length);
 
1144
  str->append('@');
 
1145
  str->qs_append(m_var_idx);
 
1146
}
 
1147
 
 
1148
 
 
1149
bool Item_splocal::set_value(THD *thd, sp_rcontext *ctx, Item **it)
 
1150
{
 
1151
  return ctx->set_variable(thd, get_var_idx(), it);
 
1152
}
 
1153
 
 
1154
 
 
1155
/*****************************************************************************
 
1156
  Item_case_expr methods
 
1157
*****************************************************************************/
 
1158
 
 
1159
Item_case_expr::Item_case_expr(uint case_expr_id)
 
1160
  :Item_sp_variable( C_STRING_WITH_LEN("case_expr")),
 
1161
   m_case_expr_id(case_expr_id)
 
1162
{
 
1163
}
 
1164
 
 
1165
 
 
1166
Item *
 
1167
Item_case_expr::this_item()
 
1168
{
 
1169
  DBUG_ASSERT(m_sp == m_thd->spcont->sp);
 
1170
 
 
1171
  return m_thd->spcont->get_case_expr(m_case_expr_id);
 
1172
}
 
1173
 
 
1174
 
 
1175
 
 
1176
const Item *
 
1177
Item_case_expr::this_item() const
 
1178
{
 
1179
  DBUG_ASSERT(m_sp == m_thd->spcont->sp);
 
1180
 
 
1181
  return m_thd->spcont->get_case_expr(m_case_expr_id);
 
1182
}
 
1183
 
 
1184
 
 
1185
Item **
 
1186
Item_case_expr::this_item_addr(THD *thd, Item **)
 
1187
{
 
1188
  DBUG_ASSERT(m_sp == thd->spcont->sp);
 
1189
 
 
1190
  return thd->spcont->get_case_expr_addr(m_case_expr_id);
 
1191
}
 
1192
 
 
1193
 
 
1194
void Item_case_expr::print(String *str, enum_query_type)
 
1195
{
 
1196
  if (str->reserve(MAX_INT_WIDTH + sizeof("case_expr@")))
 
1197
    return;                                    /* purecov: inspected */
 
1198
  VOID(str->append(STRING_WITH_LEN("case_expr@")));
 
1199
  str->qs_append(m_case_expr_id);
 
1200
}
 
1201
 
 
1202
 
 
1203
/*****************************************************************************
 
1204
  Item_name_const methods
 
1205
*****************************************************************************/
 
1206
 
 
1207
double Item_name_const::val_real()
 
1208
{
 
1209
  DBUG_ASSERT(fixed);
 
1210
  double ret= value_item->val_real();
 
1211
  null_value= value_item->null_value;
 
1212
  return ret;
 
1213
}
 
1214
 
 
1215
 
 
1216
longlong Item_name_const::val_int()
 
1217
{
 
1218
  DBUG_ASSERT(fixed);
 
1219
  longlong ret= value_item->val_int();
 
1220
  null_value= value_item->null_value;
 
1221
  return ret;
 
1222
}
 
1223
 
 
1224
 
 
1225
String *Item_name_const::val_str(String *sp)
 
1226
{
 
1227
  DBUG_ASSERT(fixed);
 
1228
  String *ret= value_item->val_str(sp);
 
1229
  null_value= value_item->null_value;
 
1230
  return ret;
 
1231
}
 
1232
 
 
1233
 
 
1234
my_decimal *Item_name_const::val_decimal(my_decimal *decimal_value)
 
1235
{
 
1236
  DBUG_ASSERT(fixed);
 
1237
  my_decimal *val= value_item->val_decimal(decimal_value);
 
1238
  null_value= value_item->null_value;
 
1239
  return val;
 
1240
}
 
1241
 
 
1242
 
 
1243
bool Item_name_const::is_null()
 
1244
{
 
1245
  return value_item->is_null();
 
1246
}
 
1247
 
 
1248
 
 
1249
Item_name_const::Item_name_const(Item *name_arg, Item *val):
 
1250
    value_item(val), name_item(name_arg)
 
1251
{
 
1252
  if (!(valid_args= name_item->basic_const_item() &&
 
1253
                    (value_item->basic_const_item() ||
 
1254
                     ((value_item->type() == FUNC_ITEM) &&
 
1255
                      ((((Item_func *) value_item)->functype() ==
 
1256
                         Item_func::COLLATE_FUNC) ||
 
1257
                      ((((Item_func *) value_item)->functype() ==
 
1258
                         Item_func::NEG_FUNC) &&
 
1259
                      (((Item_func *) value_item)->key_item()->type() !=
 
1260
                         FUNC_ITEM)))))))
 
1261
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "NAME_CONST");
 
1262
  Item::maybe_null= TRUE;
 
1263
}
 
1264
 
 
1265
 
 
1266
Item::Type Item_name_const::type() const
 
1267
{
 
1268
  /*
 
1269
    As 
 
1270
    1. one can try to create the Item_name_const passing non-constant 
 
1271
    arguments, although it's incorrect and 
 
1272
    2. the type() method can be called before the fix_fields() to get
 
1273
    type information for a further type cast, e.g. 
 
1274
    if (item->type() == FIELD_ITEM) 
 
1275
      ((Item_field *) item)->... 
 
1276
    we return NULL_ITEM in the case to avoid wrong casting.
 
1277
 
 
1278
    valid_args guarantees value_item->basic_const_item(); if type is
 
1279
    FUNC_ITEM, then we have a fudged item_func_neg() on our hands
 
1280
    and return the underlying type.
 
1281
    For Item_func_set_collation()
 
1282
    e.g. NAME_CONST('name', 'value' COLLATE collation) we return its
 
1283
    'value' argument type. 
 
1284
  */
 
1285
  if (!valid_args)
 
1286
    return NULL_ITEM;
 
1287
  Item::Type value_type= value_item->type();
 
1288
  if (value_type == FUNC_ITEM)
 
1289
  {
 
1290
    /* 
 
1291
      The second argument of NAME_CONST('name', 'value') must be 
 
1292
      a simple constant item or a NEG_FUNC/COLLATE_FUNC.
 
1293
    */
 
1294
    DBUG_ASSERT(((Item_func *) value_item)->functype() == 
 
1295
                Item_func::NEG_FUNC ||
 
1296
                ((Item_func *) value_item)->functype() == 
 
1297
                Item_func::COLLATE_FUNC);
 
1298
    return ((Item_func *) value_item)->key_item()->type();            
 
1299
  }
 
1300
  return value_type;
 
1301
}
 
1302
 
 
1303
 
 
1304
bool Item_name_const::fix_fields(THD *thd, Item **ref)
 
1305
{
 
1306
  char buf[128];
 
1307
  String *item_name;
 
1308
  String s(buf, sizeof(buf), &my_charset_bin);
 
1309
  s.length(0);
 
1310
 
 
1311
  if (value_item->fix_fields(thd, &value_item) ||
 
1312
      name_item->fix_fields(thd, &name_item) ||
 
1313
      !value_item->const_item() ||
 
1314
      !name_item->const_item() ||
 
1315
      !(item_name= name_item->val_str(&s))) // Can't have a NULL name 
 
1316
  {
 
1317
    my_error(ER_RESERVED_SYNTAX, MYF(0), "NAME_CONST");
 
1318
    return TRUE;
 
1319
  }
 
1320
  if (is_autogenerated_name)
 
1321
  {
 
1322
    set_name(item_name->ptr(), (uint) item_name->length(), system_charset_info);
 
1323
  }
 
1324
  collation.set(value_item->collation.collation, DERIVATION_IMPLICIT);
 
1325
  max_length= value_item->max_length;
 
1326
  decimals= value_item->decimals;
 
1327
  fixed= 1;
 
1328
  return FALSE;
 
1329
}
 
1330
 
 
1331
 
 
1332
void Item_name_const::print(String *str, enum_query_type query_type)
 
1333
{
 
1334
  str->append(STRING_WITH_LEN("NAME_CONST("));
 
1335
  name_item->print(str, query_type);
 
1336
  str->append(',');
 
1337
  value_item->print(str, query_type);
 
1338
  str->append(')');
 
1339
}
 
1340
 
 
1341
 
 
1342
/*
 
1343
 need a special class to adjust printing : references to aggregate functions 
 
1344
 must not be printed as refs because the aggregate functions that are added to
 
1345
 the front of select list are not printed as well.
 
1346
*/
 
1347
class Item_aggregate_ref : public Item_ref
 
1348
{
 
1349
public:
 
1350
  Item_aggregate_ref(Name_resolution_context *context_arg, Item **item,
 
1351
                  const char *table_name_arg, const char *field_name_arg)
 
1352
    :Item_ref(context_arg, item, table_name_arg, field_name_arg) {}
 
1353
 
 
1354
  virtual inline void print (String *str, enum_query_type query_type)
 
1355
  {
 
1356
    if (ref)
 
1357
      (*ref)->print(str, query_type);
 
1358
    else
 
1359
      Item_ident::print(str, query_type);
 
1360
  }
 
1361
  virtual Ref_Type ref_type() { return AGGREGATE_REF; }
 
1362
};
 
1363
 
 
1364
 
 
1365
/**
 
1366
  Move SUM items out from item tree and replace with reference.
 
1367
 
 
1368
  @param thd                    Thread handler
 
1369
  @param ref_pointer_array      Pointer to array of reference fields
 
1370
  @param fields         All fields in select
 
1371
  @param ref                    Pointer to item
 
1372
  @param skip_registered       <=> function be must skipped for registered
 
1373
                               SUM items
 
1374
 
 
1375
  @note
 
1376
    This is from split_sum_func2() for items that should be split
 
1377
 
 
1378
    All found SUM items are added FIRST in the fields list and
 
1379
    we replace the item with a reference.
 
1380
 
 
1381
    thd->fatal_error() may be called if we are out of memory
 
1382
*/
 
1383
 
 
1384
void Item::split_sum_func2(THD *thd, Item **ref_pointer_array,
 
1385
                           List<Item> &fields, Item **ref, 
 
1386
                           bool skip_registered)
 
1387
{
 
1388
  /* An item of type Item_sum  is registered <=> ref_by != 0 */ 
 
1389
  if (type() == SUM_FUNC_ITEM && skip_registered && 
 
1390
      ((Item_sum *) this)->ref_by)
 
1391
    return;                                                 
 
1392
  if ((type() != SUM_FUNC_ITEM && with_sum_func) ||
 
1393
      (type() == FUNC_ITEM &&
 
1394
       (((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC ||
 
1395
        ((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC)))
 
1396
  {
 
1397
    /* Will split complicated items and ignore simple ones */
 
1398
    split_sum_func(thd, ref_pointer_array, fields);
 
1399
  }
 
1400
  else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) &&
 
1401
           type() != SUBSELECT_ITEM &&
 
1402
           (type() != REF_ITEM ||
 
1403
           ((Item_ref*)this)->ref_type() == Item_ref::VIEW_REF))
 
1404
  {
 
1405
    /*
 
1406
      Replace item with a reference so that we can easily calculate
 
1407
      it (in case of sum functions) or copy it (in case of fields)
 
1408
 
 
1409
      The test above is to ensure we don't do a reference for things
 
1410
      that are constants (PARAM_TABLE_BIT is in effect a constant)
 
1411
      or already referenced (for example an item in HAVING)
 
1412
      Exception is Item_direct_view_ref which we need to convert to
 
1413
      Item_ref to allow fields from view being stored in tmp table.
 
1414
    */
 
1415
    Item_aggregate_ref *item_ref;
 
1416
    uint el= fields.elements;
 
1417
    Item *real_itm= real_item();
 
1418
 
 
1419
    ref_pointer_array[el]= real_itm;
 
1420
    if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context,
 
1421
                                           ref_pointer_array + el, 0, name)))
 
1422
      return;                                   // fatal_error is set
 
1423
    if (type() == SUM_FUNC_ITEM)
 
1424
      item_ref->depended_from= ((Item_sum *) this)->depended_from(); 
 
1425
    fields.push_front(real_itm);
 
1426
    thd->change_item_tree(ref, item_ref);
 
1427
  }
 
1428
}
 
1429
 
 
1430
 
 
1431
static bool
 
1432
left_is_superset(DTCollation *left, DTCollation *right)
 
1433
{
 
1434
  /* Allow convert to Unicode */
 
1435
  if (left->collation->state & MY_CS_UNICODE &&
 
1436
      (left->derivation < right->derivation ||
 
1437
       (left->derivation == right->derivation &&
 
1438
        !(right->collation->state & MY_CS_UNICODE))))
 
1439
    return TRUE;
 
1440
  /* Allow convert from ASCII */
 
1441
  if (right->repertoire == MY_REPERTOIRE_ASCII &&
 
1442
      (left->derivation < right->derivation ||
 
1443
       (left->derivation == right->derivation &&
 
1444
        !(left->repertoire == MY_REPERTOIRE_ASCII))))
 
1445
    return TRUE;
 
1446
  /* Disallow conversion otherwise */
 
1447
  return FALSE;
 
1448
}
 
1449
 
 
1450
/**
 
1451
  Aggregate two collations together taking
 
1452
  into account their coercibility (aka derivation):.
 
1453
 
 
1454
  0 == DERIVATION_EXPLICIT  - an explicitly written COLLATE clause @n
 
1455
  1 == DERIVATION_NONE      - a mix of two different collations @n
 
1456
  2 == DERIVATION_IMPLICIT  - a column @n
 
1457
  3 == DERIVATION_COERCIBLE - a string constant.
 
1458
 
 
1459
  The most important rules are:
 
1460
  -# If collations are the same:
 
1461
  chose this collation, and the strongest derivation.
 
1462
  -# If collations are different:
 
1463
  - Character sets may differ, but only if conversion without
 
1464
  data loss is possible. The caller provides flags whether
 
1465
  character set conversion attempts should be done. If no
 
1466
  flags are substituted, then the character sets must be the same.
 
1467
  Currently processed flags are:
 
1468
  MY_COLL_ALLOW_SUPERSET_CONV  - allow conversion to a superset
 
1469
  MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
 
1470
  - two EXPLICIT collations produce an error, e.g. this is wrong:
 
1471
  CONCAT(expr1 collate latin1_swedish_ci, expr2 collate latin1_german_ci)
 
1472
  - the side with smaller derivation value wins,
 
1473
  i.e. a column is stronger than a string constant,
 
1474
  an explicit COLLATE clause is stronger than a column.
 
1475
  - if derivations are the same, we have DERIVATION_NONE,
 
1476
  we'll wait for an explicit COLLATE clause which possibly can
 
1477
  come from another argument later: for example, this is valid,
 
1478
  but we don't know yet when collecting the first two arguments:
 
1479
     @code
 
1480
       CONCAT(latin1_swedish_ci_column,
 
1481
              latin1_german1_ci_column,
 
1482
              expr COLLATE latin1_german2_ci)
 
1483
  @endcode
 
1484
*/
 
1485
 
 
1486
bool DTCollation::aggregate(DTCollation &dt, uint flags)
 
1487
{
 
1488
  if (!my_charset_same(collation, dt.collation))
 
1489
  {
 
1490
    /* 
 
1491
       We do allow to use binary strings (like BLOBS)
 
1492
       together with character strings.
 
1493
       Binaries have more precedence than a character
 
1494
       string of the same derivation.
 
1495
    */
 
1496
    if (collation == &my_charset_bin)
 
1497
    {
 
1498
      if (derivation <= dt.derivation)
 
1499
        ; // Do nothing
 
1500
      else
 
1501
      {
 
1502
        set(dt); 
 
1503
      }
 
1504
    }
 
1505
    else if (dt.collation == &my_charset_bin)
 
1506
    {
 
1507
      if (dt.derivation <= derivation)
 
1508
      {
 
1509
        set(dt);
 
1510
      }
 
1511
    }
 
1512
    else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
 
1513
             left_is_superset(this, &dt))
 
1514
    {
 
1515
      // Do nothing
 
1516
    }
 
1517
    else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
 
1518
             left_is_superset(&dt, this))
 
1519
    {
 
1520
      set(dt);
 
1521
    }
 
1522
    else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
 
1523
             derivation < dt.derivation &&
 
1524
             dt.derivation >= DERIVATION_SYSCONST)
 
1525
    {
 
1526
      // Do nothing;
 
1527
    }
 
1528
    else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
 
1529
             dt.derivation < derivation &&
 
1530
             derivation >= DERIVATION_SYSCONST)
 
1531
    {
 
1532
      set(dt);
 
1533
    }
 
1534
    else
 
1535
    {
 
1536
      // Cannot apply conversion
 
1537
      set(&my_charset_bin, DERIVATION_NONE,
 
1538
          (dt.repertoire|repertoire));
 
1539
      return 1;
 
1540
    }
 
1541
  }
 
1542
  else if (derivation < dt.derivation)
 
1543
  {
 
1544
    // Do nothing
 
1545
  }
 
1546
  else if (dt.derivation < derivation)
 
1547
  {
 
1548
    set(dt);
 
1549
  }
 
1550
  else
 
1551
  { 
 
1552
    if (collation == dt.collation)
 
1553
    {
 
1554
      // Do nothing
 
1555
    }
 
1556
    else 
 
1557
    {
 
1558
      if (derivation == DERIVATION_EXPLICIT)
 
1559
      {
 
1560
        set(0, DERIVATION_NONE, 0);
 
1561
        return 1;
 
1562
      }
 
1563
      if (collation->state & MY_CS_BINSORT)
 
1564
        return 0;
 
1565
      if (dt.collation->state & MY_CS_BINSORT)
 
1566
      {
 
1567
        set(dt);
 
1568
        return 0;
 
1569
      }
 
1570
      CHARSET_INFO *bin= get_charset_by_csname(collation->csname, 
 
1571
                                               MY_CS_BINSORT,MYF(0));
 
1572
      set(bin, DERIVATION_NONE);
 
1573
    }
 
1574
  }
 
1575
  repertoire|= dt.repertoire;
 
1576
  return 0;
 
1577
}
 
1578
 
 
1579
/******************************/
 
1580
static
 
1581
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname)
 
1582
{
 
1583
  my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
 
1584
           c1.collation->name,c1.derivation_name(),
 
1585
           c2.collation->name,c2.derivation_name(),
 
1586
           fname);
 
1587
}
 
1588
 
 
1589
 
 
1590
static
 
1591
void my_coll_agg_error(DTCollation &c1, DTCollation &c2, DTCollation &c3,
 
1592
                       const char *fname)
 
1593
{
 
1594
  my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0),
 
1595
           c1.collation->name,c1.derivation_name(),
 
1596
           c2.collation->name,c2.derivation_name(),
 
1597
           c3.collation->name,c3.derivation_name(),
 
1598
           fname);
 
1599
}
 
1600
 
 
1601
 
 
1602
static
 
1603
void my_coll_agg_error(Item** args, uint count, const char *fname,
 
1604
                       int item_sep)
 
1605
{
 
1606
  if (count == 2)
 
1607
    my_coll_agg_error(args[0]->collation, args[item_sep]->collation, fname);
 
1608
  else if (count == 3)
 
1609
    my_coll_agg_error(args[0]->collation, args[item_sep]->collation,
 
1610
                      args[2*item_sep]->collation, fname);
 
1611
  else
 
1612
    my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname);
 
1613
}
 
1614
 
 
1615
 
 
1616
bool agg_item_collations(DTCollation &c, const char *fname,
 
1617
                         Item **av, uint count, uint flags, int item_sep)
 
1618
{
 
1619
  uint i;
 
1620
  Item **arg;
 
1621
  bool unknown_cs= 0;
 
1622
 
 
1623
  c.set(av[0]->collation);
 
1624
  for (i= 1, arg= &av[item_sep]; i < count; i++, arg++)
 
1625
  {
 
1626
    if (c.aggregate((*arg)->collation, flags))
 
1627
    {
 
1628
      if (c.derivation == DERIVATION_NONE &&
 
1629
          c.collation == &my_charset_bin)
 
1630
      {
 
1631
        unknown_cs= 1;
 
1632
        continue;
 
1633
      }
 
1634
      my_coll_agg_error(av, count, fname, item_sep);
 
1635
      return TRUE;
 
1636
    }
 
1637
  }
 
1638
 
 
1639
  if (unknown_cs &&
 
1640
      c.derivation != DERIVATION_EXPLICIT)
 
1641
  {
 
1642
    my_coll_agg_error(av, count, fname, item_sep);
 
1643
    return TRUE;
 
1644
  }
 
1645
 
 
1646
  if ((flags & MY_COLL_DISALLOW_NONE) &&
 
1647
      c.derivation == DERIVATION_NONE)
 
1648
  {
 
1649
    my_coll_agg_error(av, count, fname, item_sep);
 
1650
    return TRUE;
 
1651
  }
 
1652
  return FALSE;
 
1653
}
 
1654
 
 
1655
 
 
1656
bool agg_item_collations_for_comparison(DTCollation &c, const char *fname,
 
1657
                                        Item **av, uint count, uint flags)
 
1658
{
 
1659
  return (agg_item_collations(c, fname, av, count,
 
1660
                              flags | MY_COLL_DISALLOW_NONE, 1));
 
1661
}
 
1662
 
 
1663
 
 
1664
bool agg_item_set_converter(DTCollation &coll, const char *fname,
 
1665
                            Item **args, uint nargs, uint flags, int item_sep)
 
1666
{
 
1667
  Item **arg, *safe_args[2]= {NULL, NULL};
 
1668
 
 
1669
  /*
 
1670
    For better error reporting: save the first and the second argument.
 
1671
    We need this only if the the number of args is 3 or 2:
 
1672
    - for a longer argument list, "Illegal mix of collations"
 
1673
      doesn't display each argument's characteristics.
 
1674
    - if nargs is 1, then this error cannot happen.
 
1675
  */
 
1676
  if (nargs >=2 && nargs <= 3)
 
1677
  {
 
1678
    safe_args[0]= args[0];
 
1679
    safe_args[1]= args[item_sep];
 
1680
  }
 
1681
 
 
1682
  THD *thd= current_thd;
 
1683
  Query_arena *arena, backup;
 
1684
  bool res= FALSE;
 
1685
  uint i;
 
1686
  /*
 
1687
    In case we're in statement prepare, create conversion item
 
1688
    in its memory: it will be reused on each execute.
 
1689
  */
 
1690
  arena= thd->is_stmt_prepare() ? thd->activate_stmt_arena_if_needed(&backup)
 
1691
                                : NULL;
 
1692
 
 
1693
  for (i= 0, arg= args; i < nargs; i++, arg+= item_sep)
 
1694
  {
 
1695
    Item* conv;
 
1696
    uint32 dummy_offset;
 
1697
    if (!String::needs_conversion(0, (*arg)->collation.collation,
 
1698
                                  coll.collation,
 
1699
                                  &dummy_offset))
 
1700
      continue;
 
1701
 
 
1702
    if (!(conv= (*arg)->safe_charset_converter(coll.collation)) &&
 
1703
        ((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII))
 
1704
      conv= new Item_func_conv_charset(*arg, coll.collation, 1);
 
1705
 
 
1706
    if (!conv)
 
1707
    {
 
1708
      if (nargs >=2 && nargs <= 3)
 
1709
      {
 
1710
        /* restore the original arguments for better error message */
 
1711
        args[0]= safe_args[0];
 
1712
        args[item_sep]= safe_args[1];
 
1713
      }
 
1714
      my_coll_agg_error(args, nargs, fname, item_sep);
 
1715
      res= TRUE;
 
1716
      break; // we cannot return here, we need to restore "arena".
 
1717
    }
 
1718
    if ((*arg)->type() == Item::FIELD_ITEM)
 
1719
      ((Item_field *)(*arg))->no_const_subst= 1;
 
1720
    /*
 
1721
      If in statement prepare, then we create a converter for two
 
1722
      constant items, do it once and then reuse it.
 
1723
      If we're in execution of a prepared statement, arena is NULL,
 
1724
      and the conv was created in runtime memory. This can be
 
1725
      the case only if the argument is a parameter marker ('?'),
 
1726
      because for all true constants the charset converter has already
 
1727
      been created in prepare. In this case register the change for
 
1728
      rollback.
 
1729
    */
 
1730
    if (thd->is_stmt_prepare())
 
1731
      *arg= conv;
 
1732
    else
 
1733
      thd->change_item_tree(arg, conv);
 
1734
    /*
 
1735
      We do not check conv->fixed, because Item_func_conv_charset which can
 
1736
      be return by safe_charset_converter can't be fixed at creation
 
1737
    */
 
1738
    conv->fix_fields(thd, arg);
 
1739
  }
 
1740
  if (arena)
 
1741
    thd->restore_active_arena(arena, &backup);
 
1742
  return res;
 
1743
}
 
1744
 
 
1745
 
 
1746
/* 
 
1747
  Collect arguments' character sets together.
 
1748
  We allow to apply automatic character set conversion in some cases.
 
1749
  The conditions when conversion is possible are:
 
1750
  - arguments A and B have different charsets
 
1751
  - A wins according to coercibility rules
 
1752
    (i.e. a column is stronger than a string constant,
 
1753
     an explicit COLLATE clause is stronger than a column)
 
1754
  - character set of A is either superset for character set of B,
 
1755
    or B is a string constant which can be converted into the
 
1756
    character set of A without data loss.
 
1757
    
 
1758
  If all of the above is true, then it's possible to convert
 
1759
  B into the character set of A, and then compare according
 
1760
  to the collation of A.
 
1761
  
 
1762
  For functions with more than two arguments:
 
1763
 
 
1764
    collect(A,B,C) ::= collect(collect(A,B),C)
 
1765
 
 
1766
  Since this function calls THD::change_item_tree() on the passed Item **
 
1767
  pointers, it is necessary to pass the original Item **'s, not copies.
 
1768
  Otherwise their values will not be properly restored (see BUG#20769).
 
1769
  If the items are not consecutive (eg. args[2] and args[5]), use the
 
1770
  item_sep argument, ie.
 
1771
 
 
1772
    agg_item_charsets(coll, fname, &args[2], 2, flags, 3)
 
1773
 
 
1774
*/
 
1775
 
 
1776
bool agg_item_charsets(DTCollation &coll, const char *fname,
 
1777
                       Item **args, uint nargs, uint flags, int item_sep)
 
1778
{
 
1779
  if (agg_item_collations(coll, fname, args, nargs, flags, item_sep))
 
1780
    return TRUE;
 
1781
 
 
1782
  return agg_item_set_converter(coll, fname, args, nargs, flags, item_sep);
 
1783
}
 
1784
 
 
1785
 
 
1786
void Item_ident_for_show::make_field(Send_field *tmp_field)
 
1787
{
 
1788
  tmp_field->table_name= tmp_field->org_table_name= table_name;
 
1789
  tmp_field->db_name= db_name;
 
1790
  tmp_field->col_name= tmp_field->org_col_name= field->field_name;
 
1791
  tmp_field->charsetnr= field->charset()->number;
 
1792
  tmp_field->length=field->field_length;
 
1793
  tmp_field->type=field->type();
 
1794
  tmp_field->flags= field->table->maybe_null ? 
 
1795
    (field->flags & ~NOT_NULL_FLAG) : field->flags;
 
1796
  tmp_field->decimals= field->decimals();
 
1797
}
 
1798
 
 
1799
/**********************************************/
 
1800
 
 
1801
Item_field::Item_field(Field *f)
 
1802
  :Item_ident(0, NullS, *f->table_name, f->field_name),
 
1803
   item_equal(0), no_const_subst(0),
 
1804
   have_privileges(0), any_privileges(0)
 
1805
{
 
1806
  set_field(f);
 
1807
  /*
 
1808
    field_name and table_name should not point to garbage
 
1809
    if this item is to be reused
 
1810
  */
 
1811
  orig_table_name= orig_field_name= "";
 
1812
}
 
1813
 
 
1814
 
 
1815
/**
 
1816
  Constructor used inside setup_wild().
 
1817
 
 
1818
  Ensures that field, table, and database names will live as long as
 
1819
  Item_field (this is important in prepared statements).
 
1820
*/
 
1821
 
 
1822
Item_field::Item_field(THD *thd, Name_resolution_context *context_arg,
 
1823
                       Field *f)
 
1824
  :Item_ident(context_arg, f->table->s->db.str, *f->table_name, f->field_name),
 
1825
   item_equal(0), no_const_subst(0),
 
1826
   have_privileges(0), any_privileges(0)
 
1827
{
 
1828
  /*
 
1829
    We always need to provide Item_field with a fully qualified field
 
1830
    name to avoid ambiguity when executing prepared statements like
 
1831
    SELECT * from d1.t1, d2.t1; (assuming d1.t1 and d2.t1 have columns
 
1832
    with same names).
 
1833
    This is because prepared statements never deal with wildcards in
 
1834
    select list ('*') and always fix fields using fully specified path
 
1835
    (i.e. db.table.column).
 
1836
    No check for OOM: if db_name is NULL, we'll just get
 
1837
    "Field not found" error.
 
1838
    We need to copy db_name, table_name and field_name because they must
 
1839
    be allocated in the statement memory, not in table memory (the table
 
1840
    structure can go away and pop up again between subsequent executions
 
1841
    of a prepared statement or after the close_tables_for_reopen() call
 
1842
    in mysql_multi_update_prepare() or due to wildcard expansion in stored
 
1843
    procedures).
 
1844
  */
 
1845
  {
 
1846
    if (db_name)
 
1847
      orig_db_name= thd->strdup(db_name);
 
1848
    if (table_name)
 
1849
      orig_table_name= thd->strdup(table_name);
 
1850
    if (field_name)
 
1851
      orig_field_name= thd->strdup(field_name);
 
1852
    /*
 
1853
      We don't restore 'name' in cleanup because it's not changed
 
1854
      during execution. Still we need it to point to persistent
 
1855
      memory if this item is to be reused.
 
1856
    */
 
1857
    name= (char*) orig_field_name;
 
1858
  }
 
1859
  set_field(f);
 
1860
}
 
1861
 
 
1862
 
 
1863
Item_field::Item_field(Name_resolution_context *context_arg,
 
1864
                       const char *db_arg,const char *table_name_arg,
 
1865
                       const char *field_name_arg)
 
1866
  :Item_ident(context_arg, db_arg,table_name_arg,field_name_arg),
 
1867
   field(0), result_field(0), item_equal(0), no_const_subst(0),
 
1868
   have_privileges(0), any_privileges(0)
 
1869
{
 
1870
  SELECT_LEX *select= current_thd->lex->current_select;
 
1871
  collation.set(DERIVATION_IMPLICIT);
 
1872
  if (select && select->parsing_place != IN_HAVING)
 
1873
      select->select_n_where_fields++;
 
1874
}
 
1875
 
 
1876
/**
 
1877
  Constructor need to process subselect with temporary tables (see Item)
 
1878
*/
 
1879
 
 
1880
Item_field::Item_field(THD *thd, Item_field *item)
 
1881
  :Item_ident(thd, item),
 
1882
   field(item->field),
 
1883
   result_field(item->result_field),
 
1884
   item_equal(item->item_equal),
 
1885
   no_const_subst(item->no_const_subst),
 
1886
   have_privileges(item->have_privileges),
 
1887
   any_privileges(item->any_privileges)
 
1888
{
 
1889
  collation.set(DERIVATION_IMPLICIT);
 
1890
}
 
1891
 
 
1892
void Item_field::set_field(Field *field_par)
 
1893
{
 
1894
  field=result_field=field_par;                 // for easy coding with fields
 
1895
  maybe_null=field->maybe_null();
 
1896
  decimals= field->decimals();
 
1897
  max_length= field_par->max_display_length();
 
1898
  table_name= *field_par->table_name;
 
1899
  field_name= field_par->field_name;
 
1900
  db_name= field_par->table->s->db.str;
 
1901
  alias_name_used= field_par->table->alias_name_used;
 
1902
  unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
 
1903
  collation.set(field_par->charset(), field_par->derivation());
 
1904
  fixed= 1;
 
1905
  if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
 
1906
    any_privileges= 0;
 
1907
}
 
1908
 
 
1909
 
 
1910
/**
 
1911
  Reset this item to point to a field from the new temporary table.
 
1912
  This is used when we create a new temporary table for each execution
 
1913
  of prepared statement.
 
1914
*/
 
1915
 
 
1916
void Item_field::reset_field(Field *f)
 
1917
{
 
1918
  set_field(f);
 
1919
  /* 'name' is pointing at field->field_name of old field */
 
1920
  name= (char*) f->field_name;
 
1921
}
 
1922
 
 
1923
const char *Item_ident::full_name() const
 
1924
{
 
1925
  char *tmp;
 
1926
  if (!table_name || !field_name)
 
1927
    return field_name ? field_name : name ? name : "tmp_field";
 
1928
  if (db_name && db_name[0])
 
1929
  {
 
1930
    tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
 
1931
                          (uint) strlen(field_name)+3);
 
1932
    strxmov(tmp,db_name,".",table_name,".",field_name,NullS);
 
1933
  }
 
1934
  else
 
1935
  {
 
1936
    if (table_name[0])
 
1937
    {
 
1938
      tmp= (char*) sql_alloc((uint) strlen(table_name) +
 
1939
                             (uint) strlen(field_name) + 2);
 
1940
      strxmov(tmp, table_name, ".", field_name, NullS);
 
1941
    }
 
1942
    else
 
1943
      tmp= (char*) field_name;
 
1944
  }
 
1945
  return tmp;
 
1946
}
 
1947
 
 
1948
void Item_ident::print(String *str, enum_query_type query_type)
 
1949
{
 
1950
  THD *thd= current_thd;
 
1951
  char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
 
1952
  const char *d_name= db_name, *t_name= table_name;
 
1953
  if (lower_case_table_names== 1 ||
 
1954
      (lower_case_table_names == 2 && !alias_name_used))
 
1955
  {
 
1956
    if (table_name && table_name[0])
 
1957
    {
 
1958
      strmov(t_name_buff, table_name);
 
1959
      my_casedn_str(files_charset_info, t_name_buff);
 
1960
      t_name= t_name_buff;
 
1961
    }
 
1962
    if (db_name && db_name[0])
 
1963
    {
 
1964
      strmov(d_name_buff, db_name);
 
1965
      my_casedn_str(files_charset_info, d_name_buff);
 
1966
      d_name= d_name_buff;
 
1967
    }
 
1968
  }
 
1969
 
 
1970
  if (!table_name || !field_name || !field_name[0])
 
1971
  {
 
1972
    const char *nm= (field_name && field_name[0]) ?
 
1973
                      field_name : name ? name : "tmp_field";
 
1974
    append_identifier(thd, str, nm, (uint) strlen(nm));
 
1975
    return;
 
1976
  }
 
1977
  if (db_name && db_name[0] && !alias_name_used)
 
1978
  {
 
1979
    if (!(cached_table && cached_table->belong_to_view &&
 
1980
          cached_table->belong_to_view->compact_view_format))
 
1981
    {
 
1982
      append_identifier(thd, str, d_name, (uint)strlen(d_name));
 
1983
      str->append('.');
 
1984
    }
 
1985
    append_identifier(thd, str, t_name, (uint)strlen(t_name));
 
1986
    str->append('.');
 
1987
    append_identifier(thd, str, field_name, (uint)strlen(field_name));
 
1988
  }
 
1989
  else
 
1990
  {
 
1991
    if (table_name[0])
 
1992
    {
 
1993
      append_identifier(thd, str, t_name, (uint) strlen(t_name));
 
1994
      str->append('.');
 
1995
      append_identifier(thd, str, field_name, (uint) strlen(field_name));
 
1996
    }
 
1997
    else
 
1998
      append_identifier(thd, str, field_name, (uint) strlen(field_name));
 
1999
  }
 
2000
}
 
2001
 
 
2002
/* ARGSUSED */
 
2003
String *Item_field::val_str(String *str)
 
2004
{
 
2005
  DBUG_ASSERT(fixed == 1);
 
2006
  if ((null_value=field->is_null()))
 
2007
    return 0;
 
2008
  str->set_charset(str_value.charset());
 
2009
  return field->val_str(str,&str_value);
 
2010
}
 
2011
 
 
2012
 
 
2013
double Item_field::val_real()
 
2014
{
 
2015
  DBUG_ASSERT(fixed == 1);
 
2016
  if ((null_value=field->is_null()))
 
2017
    return 0.0;
 
2018
  return field->val_real();
 
2019
}
 
2020
 
 
2021
 
 
2022
longlong Item_field::val_int()
 
2023
{
 
2024
  DBUG_ASSERT(fixed == 1);
 
2025
  if ((null_value=field->is_null()))
 
2026
    return 0;
 
2027
  return field->val_int();
 
2028
}
 
2029
 
 
2030
 
 
2031
my_decimal *Item_field::val_decimal(my_decimal *decimal_value)
 
2032
{
 
2033
  if ((null_value= field->is_null()))
 
2034
    return 0;
 
2035
  return field->val_decimal(decimal_value);
 
2036
}
 
2037
 
 
2038
 
 
2039
String *Item_field::str_result(String *str)
 
2040
{
 
2041
  if ((null_value=result_field->is_null()))
 
2042
    return 0;
 
2043
  str->set_charset(str_value.charset());
 
2044
  return result_field->val_str(str,&str_value);
 
2045
}
 
2046
 
 
2047
bool Item_field::get_date(MYSQL_TIME *ltime,uint fuzzydate)
 
2048
{
 
2049
  if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
 
2050
  {
 
2051
    bzero((char*) ltime,sizeof(*ltime));
 
2052
    return 1;
 
2053
  }
 
2054
  return 0;
 
2055
}
 
2056
 
 
2057
bool Item_field::get_date_result(MYSQL_TIME *ltime,uint fuzzydate)
 
2058
{
 
2059
  if ((null_value=result_field->is_null()) ||
 
2060
      result_field->get_date(ltime,fuzzydate))
 
2061
  {
 
2062
    bzero((char*) ltime,sizeof(*ltime));
 
2063
    return 1;
 
2064
  }
 
2065
  return 0;
 
2066
}
 
2067
 
 
2068
bool Item_field::get_time(MYSQL_TIME *ltime)
 
2069
{
 
2070
  if ((null_value=field->is_null()) || field->get_time(ltime))
 
2071
  {
 
2072
    bzero((char*) ltime,sizeof(*ltime));
 
2073
    return 1;
 
2074
  }
 
2075
  return 0;
 
2076
}
 
2077
 
 
2078
double Item_field::val_result()
 
2079
{
 
2080
  if ((null_value=result_field->is_null()))
 
2081
    return 0.0;
 
2082
  return result_field->val_real();
 
2083
}
 
2084
 
 
2085
longlong Item_field::val_int_result()
 
2086
{
 
2087
  if ((null_value=result_field->is_null()))
 
2088
    return 0;
 
2089
  return result_field->val_int();
 
2090
}
 
2091
 
 
2092
 
 
2093
my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value)
 
2094
{
 
2095
  if ((null_value= result_field->is_null()))
 
2096
    return 0;
 
2097
  return result_field->val_decimal(decimal_value);
 
2098
}
 
2099
 
 
2100
 
 
2101
bool Item_field::val_bool_result()
 
2102
{
 
2103
  if ((null_value= result_field->is_null()))
 
2104
    return FALSE;
 
2105
  switch (result_field->result_type()) {
 
2106
  case INT_RESULT:
 
2107
    return result_field->val_int() != 0;
 
2108
  case DECIMAL_RESULT:
 
2109
  {
 
2110
    my_decimal decimal_value;
 
2111
    my_decimal *val= result_field->val_decimal(&decimal_value);
 
2112
    if (val)
 
2113
      return !my_decimal_is_zero(val);
 
2114
    return 0;
 
2115
  }
 
2116
  case REAL_RESULT:
 
2117
  case STRING_RESULT:
 
2118
    return result_field->val_real() != 0.0;
 
2119
  case ROW_RESULT:
 
2120
  default:
 
2121
    DBUG_ASSERT(0);
 
2122
    return 0;                                   // Shut up compiler
 
2123
  }
 
2124
}
 
2125
 
 
2126
 
 
2127
bool Item_field::is_null_result()
 
2128
{
 
2129
  return (null_value=result_field->is_null());
 
2130
}
 
2131
 
 
2132
 
 
2133
bool Item_field::eq(const Item *item, bool binary_cmp) const
 
2134
{
 
2135
  Item *real_item= ((Item *) item)->real_item();
 
2136
  if (real_item->type() != FIELD_ITEM)
 
2137
    return 0;
 
2138
  
 
2139
  Item_field *item_field= (Item_field*) real_item;
 
2140
  if (item_field->field && field)
 
2141
    return item_field->field == field;
 
2142
  /*
 
2143
    We may come here when we are trying to find a function in a GROUP BY
 
2144
    clause from the select list.
 
2145
    In this case the '100 % correct' way to do this would be to first
 
2146
    run fix_fields() on the GROUP BY item and then retry this function, but
 
2147
    I think it's better to relax the checking a bit as we will in
 
2148
    most cases do the correct thing by just checking the field name.
 
2149
    (In cases where we would choose wrong we would have to generate a
 
2150
    ER_NON_UNIQ_ERROR).
 
2151
  */
 
2152
  return (!my_strcasecmp(system_charset_info, item_field->name,
 
2153
                         field_name) &&
 
2154
          (!item_field->table_name || !table_name ||
 
2155
           (!my_strcasecmp(table_alias_charset, item_field->table_name,
 
2156
                           table_name) &&
 
2157
            (!item_field->db_name || !db_name ||
 
2158
             (item_field->db_name && !strcmp(item_field->db_name,
 
2159
                                             db_name))))));
 
2160
}
 
2161
 
 
2162
 
 
2163
table_map Item_field::used_tables() const
 
2164
{
 
2165
  if (field->table->const_table)
 
2166
    return 0;                                   // const item
 
2167
  return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
 
2168
}
 
2169
 
 
2170
 
 
2171
Item *Item_field::get_tmp_table_item(THD *thd)
 
2172
{
 
2173
  Item_field *new_item= new Item_field(thd, this);
 
2174
  if (new_item)
 
2175
    new_item->field= new_item->result_field;
 
2176
  return new_item;
 
2177
}
 
2178
 
 
2179
longlong Item_field::val_int_endpoint(bool left_endp, bool *incl_endp)
 
2180
{
 
2181
  longlong res= val_int();
 
2182
  return null_value? LONGLONG_MIN : res;
 
2183
}
 
2184
 
 
2185
/**
 
2186
  Create an item from a string we KNOW points to a valid longlong
 
2187
  end \\0 terminated number string.
 
2188
  This is always 'signed'. Unsigned values are created with Item_uint()
 
2189
*/
 
2190
 
 
2191
Item_int::Item_int(const char *str_arg, uint length)
 
2192
{
 
2193
  char *end_ptr= (char*) str_arg + length;
 
2194
  int error;
 
2195
  value= my_strtoll10(str_arg, &end_ptr, &error);
 
2196
  max_length= (uint) (end_ptr - str_arg);
 
2197
  name= (char*) str_arg;
 
2198
  fixed= 1;
 
2199
}
 
2200
 
 
2201
 
 
2202
my_decimal *Item_int::val_decimal(my_decimal *decimal_value)
 
2203
{
 
2204
  int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_value);
 
2205
  return decimal_value;
 
2206
}
 
2207
 
 
2208
String *Item_int::val_str(String *str)
 
2209
{
 
2210
  // following assert is redundant, because fixed=1 assigned in constructor
 
2211
  DBUG_ASSERT(fixed == 1);
 
2212
  str->set_int(value, unsigned_flag, &my_charset_bin);
 
2213
  return str;
 
2214
}
 
2215
 
 
2216
void Item_int::print(String *str, enum_query_type query_type)
 
2217
{
 
2218
  // my_charset_bin is good enough for numbers
 
2219
  str_value.set_int(value, unsigned_flag, &my_charset_bin);
 
2220
  str->append(str_value);
 
2221
}
 
2222
 
 
2223
 
 
2224
Item_uint::Item_uint(const char *str_arg, uint length):
 
2225
  Item_int(str_arg, length)
 
2226
{
 
2227
  unsigned_flag= 1;
 
2228
}
 
2229
 
 
2230
 
 
2231
Item_uint::Item_uint(const char *str_arg, longlong i, uint length):
 
2232
  Item_int(str_arg, i, length)
 
2233
{
 
2234
  unsigned_flag= 1;
 
2235
}
 
2236
 
 
2237
 
 
2238
String *Item_uint::val_str(String *str)
 
2239
{
 
2240
  // following assert is redundant, because fixed=1 assigned in constructor
 
2241
  DBUG_ASSERT(fixed == 1);
 
2242
  str->set((ulonglong) value, &my_charset_bin);
 
2243
  return str;
 
2244
}
 
2245
 
 
2246
 
 
2247
void Item_uint::print(String *str, enum_query_type query_type)
 
2248
{
 
2249
  // latin1 is good enough for numbers
 
2250
  str_value.set((ulonglong) value, default_charset());
 
2251
  str->append(str_value);
 
2252
}
 
2253
 
 
2254
 
 
2255
Item_decimal::Item_decimal(const char *str_arg, uint length,
 
2256
                           CHARSET_INFO *charset)
 
2257
{
 
2258
  str2my_decimal(E_DEC_FATAL_ERROR, str_arg, length, charset, &decimal_value);
 
2259
  name= (char*) str_arg;
 
2260
  decimals= (uint8) decimal_value.frac;
 
2261
  fixed= 1;
 
2262
  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
 
2263
                                                           decimals,
 
2264
                                                           decimals,
 
2265
                                                           unsigned_flag);
 
2266
}
 
2267
 
 
2268
Item_decimal::Item_decimal(longlong val, bool unsig)
 
2269
{
 
2270
  int2my_decimal(E_DEC_FATAL_ERROR, val, unsig, &decimal_value);
 
2271
  decimals= (uint8) decimal_value.frac;
 
2272
  fixed= 1;
 
2273
  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
 
2274
                                                           decimals,
 
2275
                                                           decimals,
 
2276
                                                           unsigned_flag);
 
2277
}
 
2278
 
 
2279
 
 
2280
Item_decimal::Item_decimal(double val, int precision, int scale)
 
2281
{
 
2282
  double2my_decimal(E_DEC_FATAL_ERROR, val, &decimal_value);
 
2283
  decimals= (uint8) decimal_value.frac;
 
2284
  fixed= 1;
 
2285
  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
 
2286
                                                           decimals,
 
2287
                                                           decimals,
 
2288
                                                           unsigned_flag);
 
2289
}
 
2290
 
 
2291
 
 
2292
Item_decimal::Item_decimal(const char *str, const my_decimal *val_arg,
 
2293
                           uint decimal_par, uint length)
 
2294
{
 
2295
  my_decimal2decimal(val_arg, &decimal_value);
 
2296
  name= (char*) str;
 
2297
  decimals= (uint8) decimal_par;
 
2298
  max_length= length;
 
2299
  fixed= 1;
 
2300
}
 
2301
 
 
2302
 
 
2303
Item_decimal::Item_decimal(my_decimal *value_par)
 
2304
{
 
2305
  my_decimal2decimal(value_par, &decimal_value);
 
2306
  decimals= (uint8) decimal_value.frac;
 
2307
  fixed= 1;
 
2308
  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
 
2309
                                                           decimals,
 
2310
                                                           decimals,
 
2311
                                                           unsigned_flag);
 
2312
}
 
2313
 
 
2314
 
 
2315
Item_decimal::Item_decimal(const uchar *bin, int precision, int scale)
 
2316
{
 
2317
  binary2my_decimal(E_DEC_FATAL_ERROR, bin,
 
2318
                    &decimal_value, precision, scale);
 
2319
  decimals= (uint8) decimal_value.frac;
 
2320
  fixed= 1;
 
2321
  max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
 
2322
                                                           unsigned_flag);
 
2323
}
 
2324
 
 
2325
 
 
2326
longlong Item_decimal::val_int()
 
2327
{
 
2328
  longlong result;
 
2329
  my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &result);
 
2330
  return result;
 
2331
}
 
2332
 
 
2333
double Item_decimal::val_real()
 
2334
{
 
2335
  double result;
 
2336
  my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
 
2337
  return result;
 
2338
}
 
2339
 
 
2340
String *Item_decimal::val_str(String *result)
 
2341
{
 
2342
  result->set_charset(&my_charset_bin);
 
2343
  my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, result);
 
2344
  return result;
 
2345
}
 
2346
 
 
2347
void Item_decimal::print(String *str, enum_query_type query_type)
 
2348
{
 
2349
  my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, &str_value);
 
2350
  str->append(str_value);
 
2351
}
 
2352
 
 
2353
 
 
2354
bool Item_decimal::eq(const Item *item, bool binary_cmp) const
 
2355
{
 
2356
  if (type() == item->type() && item->basic_const_item())
 
2357
  {
 
2358
    /*
 
2359
      We need to cast off const to call val_decimal(). This should
 
2360
      be OK for a basic constant. Additionally, we can pass 0 as
 
2361
      a true decimal constant will return its internal decimal
 
2362
      storage and ignore the argument.
 
2363
    */
 
2364
    Item *arg= (Item*) item;
 
2365
    my_decimal *value= arg->val_decimal(0);
 
2366
    return !my_decimal_cmp(&decimal_value, value);
 
2367
  }
 
2368
  return 0;
 
2369
}
 
2370
 
 
2371
 
 
2372
void Item_decimal::set_decimal_value(my_decimal *value_par)
 
2373
{
 
2374
  my_decimal2decimal(value_par, &decimal_value);
 
2375
  decimals= (uint8) decimal_value.frac;
 
2376
  unsigned_flag= !decimal_value.sign();
 
2377
  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
 
2378
                                                           decimals,
 
2379
                                                           decimals,
 
2380
                                                           unsigned_flag);
 
2381
}
 
2382
 
 
2383
 
 
2384
String *Item_float::val_str(String *str)
 
2385
{
 
2386
  // following assert is redundant, because fixed=1 assigned in constructor
 
2387
  DBUG_ASSERT(fixed == 1);
 
2388
  str->set_real(value,decimals,&my_charset_bin);
 
2389
  return str;
 
2390
}
 
2391
 
 
2392
 
 
2393
my_decimal *Item_float::val_decimal(my_decimal *decimal_value)
 
2394
{
 
2395
  // following assert is redundant, because fixed=1 assigned in constructor
 
2396
  DBUG_ASSERT(fixed == 1);
 
2397
  double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_value);
 
2398
  return (decimal_value);
 
2399
}
 
2400
 
 
2401
 
 
2402
void Item_string::print(String *str, enum_query_type query_type)
 
2403
{
 
2404
  if (query_type == QT_ORDINARY && is_cs_specified())
 
2405
  {
 
2406
    str->append('_');
 
2407
    str->append(collation.collation->csname);
 
2408
  }
 
2409
 
 
2410
  str->append('\'');
 
2411
 
 
2412
  if (query_type == QT_ORDINARY ||
 
2413
      my_charset_same(str_value.charset(), system_charset_info))
 
2414
  {
 
2415
    str_value.print(str);
 
2416
  }
 
2417
  else
 
2418
  {
 
2419
    THD *thd= current_thd;
 
2420
    LEX_STRING utf8_lex_str;
 
2421
 
 
2422
    thd->convert_string(&utf8_lex_str,
 
2423
                        system_charset_info,
 
2424
                        str_value.c_ptr_safe(),
 
2425
                        str_value.length(),
 
2426
                        str_value.charset());
 
2427
 
 
2428
    String utf8_str(utf8_lex_str.str,
 
2429
                    utf8_lex_str.length,
 
2430
                    system_charset_info);
 
2431
 
 
2432
    utf8_str.print(str);
 
2433
  }
 
2434
 
 
2435
  str->append('\'');
 
2436
}
 
2437
 
 
2438
 
 
2439
double 
 
2440
double_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end)
 
2441
{
 
2442
  int error;
 
2443
  char *org_end;
 
2444
  double tmp;
 
2445
 
 
2446
  org_end= end;
 
2447
  tmp= my_strntod(cs, (char*) cptr, end - cptr, &end, &error);
 
2448
  if (error || (end != org_end && !check_if_only_end_space(cs, end, org_end)))
 
2449
  {
 
2450
    /*
 
2451
      We can use str_value.ptr() here as Item_string is gurantee to put an
 
2452
      end \0 here.
 
2453
    */
 
2454
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2455
                        ER_TRUNCATED_WRONG_VALUE,
 
2456
                        ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
 
2457
                        cptr);
 
2458
  }
 
2459
  return tmp;
 
2460
}
 
2461
 
 
2462
 
 
2463
double Item_string::val_real()
 
2464
{
 
2465
  DBUG_ASSERT(fixed == 1);
 
2466
  return double_from_string_with_check (str_value.charset(), str_value.ptr(), 
 
2467
                                        (char *) str_value.ptr() + str_value.length());
 
2468
}
 
2469
 
 
2470
 
 
2471
longlong 
 
2472
longlong_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end)
 
2473
{
 
2474
  int err;
 
2475
  longlong tmp;
 
2476
  char *org_end= end;
 
2477
 
 
2478
  tmp= (*(cs->cset->strtoll10))(cs, cptr, &end, &err);
 
2479
  /*
 
2480
    TODO: Give error if we wanted a signed integer and we got an unsigned
 
2481
    one
 
2482
  */
 
2483
  if (!current_thd->no_errors &&
 
2484
      (err > 0 ||
 
2485
       (end != org_end && !check_if_only_end_space(cs, end, org_end))))
 
2486
  {
 
2487
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2488
                        ER_TRUNCATED_WRONG_VALUE,
 
2489
                        ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
 
2490
                        cptr);
 
2491
  }
 
2492
  return tmp;
 
2493
}
 
2494
 
 
2495
 
 
2496
/**
 
2497
  @todo
 
2498
  Give error if we wanted a signed integer and we got an unsigned one
 
2499
*/
 
2500
longlong Item_string::val_int()
 
2501
{
 
2502
  DBUG_ASSERT(fixed == 1);
 
2503
  return longlong_from_string_with_check(str_value.charset(), str_value.ptr(),
 
2504
                             (char *) str_value.ptr()+ str_value.length());
 
2505
}
 
2506
 
 
2507
 
 
2508
my_decimal *Item_string::val_decimal(my_decimal *decimal_value)
 
2509
{
 
2510
  return val_decimal_from_string(decimal_value);
 
2511
}
 
2512
 
 
2513
 
 
2514
bool Item_null::eq(const Item *item, bool binary_cmp) const
 
2515
{ return item->type() == type(); }
 
2516
 
 
2517
 
 
2518
double Item_null::val_real()
 
2519
{
 
2520
  // following assert is redundant, because fixed=1 assigned in constructor
 
2521
  DBUG_ASSERT(fixed == 1);
 
2522
  null_value=1;
 
2523
  return 0.0;
 
2524
}
 
2525
longlong Item_null::val_int()
 
2526
{
 
2527
  // following assert is redundant, because fixed=1 assigned in constructor
 
2528
  DBUG_ASSERT(fixed == 1);
 
2529
  null_value=1;
 
2530
  return 0;
 
2531
}
 
2532
/* ARGSUSED */
 
2533
String *Item_null::val_str(String *str)
 
2534
{
 
2535
  // following assert is redundant, because fixed=1 assigned in constructor
 
2536
  DBUG_ASSERT(fixed == 1);
 
2537
  null_value=1;
 
2538
  return 0;
 
2539
}
 
2540
 
 
2541
my_decimal *Item_null::val_decimal(my_decimal *decimal_value)
 
2542
{
 
2543
  return 0;
 
2544
}
 
2545
 
 
2546
 
 
2547
Item *Item_null::safe_charset_converter(CHARSET_INFO *tocs)
 
2548
{
 
2549
  collation.set(tocs);
 
2550
  return this;
 
2551
}
 
2552
 
 
2553
/*********************** Item_param related ******************************/
 
2554
 
 
2555
/** 
 
2556
  Default function of Item_param::set_param_func, so in case
 
2557
  of malformed packet the server won't SIGSEGV.
 
2558
*/
 
2559
 
 
2560
static void
 
2561
default_set_param_func(Item_param *param,
 
2562
                       uchar **pos __attribute__((unused)),
 
2563
                       ulong len __attribute__((unused)))
 
2564
{
 
2565
  param->set_null();
 
2566
}
 
2567
 
 
2568
 
 
2569
Item_param::Item_param(uint pos_in_query_arg) :
 
2570
  state(NO_VALUE),
 
2571
  item_result_type(STRING_RESULT),
 
2572
  /* Don't pretend to be a literal unless value for this item is set. */
 
2573
  item_type(PARAM_ITEM),
 
2574
  param_type(MYSQL_TYPE_VARCHAR),
 
2575
  pos_in_query(pos_in_query_arg),
 
2576
  set_param_func(default_set_param_func),
 
2577
  limit_clause_param(FALSE)
 
2578
{
 
2579
  name= (char*) "?";
 
2580
  /* 
 
2581
    Since we can't say whenever this item can be NULL or cannot be NULL
 
2582
    before mysql_stmt_execute(), so we assuming that it can be NULL until
 
2583
    value is set.
 
2584
  */
 
2585
  maybe_null= 1;
 
2586
  cnvitem= new Item_string("", 0, &my_charset_bin, DERIVATION_COERCIBLE);
 
2587
  cnvstr.set(cnvbuf, sizeof(cnvbuf), &my_charset_bin);
 
2588
}
 
2589
 
 
2590
 
 
2591
void Item_param::set_null()
 
2592
{
 
2593
  DBUG_ENTER("Item_param::set_null");
 
2594
  /* These are cleared after each execution by reset() method */
 
2595
  null_value= 1;
 
2596
  /* 
 
2597
    Because of NULL and string values we need to set max_length for each new
 
2598
    placeholder value: user can submit NULL for any placeholder type, and 
 
2599
    string length can be different in each execution.
 
2600
  */
 
2601
  max_length= 0;
 
2602
  decimals= 0;
 
2603
  state= NULL_VALUE;
 
2604
  item_type= Item::NULL_ITEM;
 
2605
  DBUG_VOID_RETURN;
 
2606
}
 
2607
 
 
2608
void Item_param::set_int(longlong i, uint32 max_length_arg)
 
2609
{
 
2610
  DBUG_ENTER("Item_param::set_int");
 
2611
  value.integer= (longlong) i;
 
2612
  state= INT_VALUE;
 
2613
  max_length= max_length_arg;
 
2614
  decimals= 0;
 
2615
  maybe_null= 0;
 
2616
  DBUG_VOID_RETURN;
 
2617
}
 
2618
 
 
2619
void Item_param::set_double(double d)
 
2620
{
 
2621
  DBUG_ENTER("Item_param::set_double");
 
2622
  value.real= d;
 
2623
  state= REAL_VALUE;
 
2624
  max_length= DBL_DIG + 8;
 
2625
  decimals= NOT_FIXED_DEC;
 
2626
  maybe_null= 0;
 
2627
  DBUG_VOID_RETURN;
 
2628
}
 
2629
 
 
2630
 
 
2631
/**
 
2632
  Set decimal parameter value from string.
 
2633
 
 
2634
  @param str      character string
 
2635
  @param length   string length
 
2636
 
 
2637
  @note
 
2638
    As we use character strings to send decimal values in
 
2639
    binary protocol, we use str2my_decimal to convert it to
 
2640
    internal decimal value.
 
2641
*/
 
2642
 
 
2643
void Item_param::set_decimal(const char *str, ulong length)
 
2644
{
 
2645
  char *end;
 
2646
  DBUG_ENTER("Item_param::set_decimal");
 
2647
 
 
2648
  end= (char*) str+length;
 
2649
  str2my_decimal(E_DEC_FATAL_ERROR, str, &decimal_value, &end);
 
2650
  state= DECIMAL_VALUE;
 
2651
  decimals= decimal_value.frac;
 
2652
  max_length=
 
2653
    my_decimal_precision_to_length_no_truncation(decimal_value.precision(),
 
2654
                                                 decimals, unsigned_flag);
 
2655
  maybe_null= 0;
 
2656
  DBUG_VOID_RETURN;
 
2657
}
 
2658
 
 
2659
 
 
2660
/**
 
2661
  Set parameter value from MYSQL_TIME value.
 
2662
 
 
2663
  @param tm              datetime value to set (time_type is ignored)
 
2664
  @param type            type of datetime value
 
2665
  @param max_length_arg  max length of datetime value as string
 
2666
 
 
2667
  @note
 
2668
    If we value to be stored is not normalized, zero value will be stored
 
2669
    instead and proper warning will be produced. This function relies on
 
2670
    the fact that even wrong value sent over binary protocol fits into
 
2671
    MAX_DATE_STRING_REP_LENGTH buffer.
 
2672
*/
 
2673
void Item_param::set_time(MYSQL_TIME *tm, timestamp_type time_type,
 
2674
                          uint32 max_length_arg)
 
2675
 
2676
  DBUG_ENTER("Item_param::set_time");
 
2677
 
 
2678
  value.time= *tm;
 
2679
  value.time.time_type= time_type;
 
2680
 
 
2681
  if (value.time.year > 9999 || value.time.month > 12 ||
 
2682
      value.time.day > 31 ||
 
2683
      (time_type != MYSQL_TIMESTAMP_TIME && value.time.hour > 23) ||
 
2684
      value.time.minute > 59 || value.time.second > 59)
 
2685
  {
 
2686
    char buff[MAX_DATE_STRING_REP_LENGTH];
 
2687
    uint length= my_TIME_to_str(&value.time, buff);
 
2688
    make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2689
                                 buff, length, time_type, 0);
 
2690
    set_zero_time(&value.time, MYSQL_TIMESTAMP_ERROR);
 
2691
  }
 
2692
 
 
2693
  state= TIME_VALUE;
 
2694
  maybe_null= 0;
 
2695
  max_length= max_length_arg;
 
2696
  decimals= 0;
 
2697
  DBUG_VOID_RETURN;
 
2698
}
 
2699
 
 
2700
 
 
2701
bool Item_param::set_str(const char *str, ulong length)
 
2702
{
 
2703
  DBUG_ENTER("Item_param::set_str");
 
2704
  /*
 
2705
    Assign string with no conversion: data is converted only after it's
 
2706
    been written to the binary log.
 
2707
  */
 
2708
  uint dummy_errors;
 
2709
  if (str_value.copy(str, length, &my_charset_bin, &my_charset_bin,
 
2710
                     &dummy_errors))
 
2711
    DBUG_RETURN(TRUE);
 
2712
  state= STRING_VALUE;
 
2713
  max_length= length;
 
2714
  maybe_null= 0;
 
2715
  /* max_length and decimals are set after charset conversion */
 
2716
  /* sic: str may be not null-terminated, don't add DBUG_PRINT here */
 
2717
  DBUG_RETURN(FALSE);
 
2718
}
 
2719
 
 
2720
 
 
2721
bool Item_param::set_longdata(const char *str, ulong length)
 
2722
{
 
2723
  DBUG_ENTER("Item_param::set_longdata");
 
2724
 
 
2725
  /*
 
2726
    If client character set is multibyte, end of long data packet
 
2727
    may hit at the middle of a multibyte character.  Additionally,
 
2728
    if binary log is open we must write long data value to the
 
2729
    binary log in character set of client. This is why we can't
 
2730
    convert long data to connection character set as it comes
 
2731
    (here), and first have to concatenate all pieces together,
 
2732
    write query to the binary log and only then perform conversion.
 
2733
  */
 
2734
  if (str_value.append(str, length, &my_charset_bin))
 
2735
    DBUG_RETURN(TRUE);
 
2736
  state= LONG_DATA_VALUE;
 
2737
  maybe_null= 0;
 
2738
 
 
2739
  DBUG_RETURN(FALSE);
 
2740
}
 
2741
 
 
2742
 
 
2743
/**
 
2744
  Set parameter value from user variable value.
 
2745
 
 
2746
  @param thd   Current thread
 
2747
  @param entry User variable structure (NULL means use NULL value)
 
2748
 
 
2749
  @retval
 
2750
    0 OK
 
2751
  @retval
 
2752
    1 Out of memory
 
2753
*/
 
2754
 
 
2755
bool Item_param::set_from_user_var(THD *thd, const user_var_entry *entry)
 
2756
{
 
2757
  DBUG_ENTER("Item_param::set_from_user_var");
 
2758
  if (entry && entry->value)
 
2759
  {
 
2760
    item_result_type= entry->type;
 
2761
    unsigned_flag= entry->unsigned_flag;
 
2762
    if (limit_clause_param)
 
2763
    {
 
2764
      my_bool unused;
 
2765
      set_int(entry->val_int(&unused), MY_INT64_NUM_DECIMAL_DIGITS);
 
2766
      item_type= Item::INT_ITEM;
 
2767
      DBUG_RETURN(!unsigned_flag && value.integer < 0 ? 1 : 0);
 
2768
    }
 
2769
    switch (item_result_type) {
 
2770
    case REAL_RESULT:
 
2771
      set_double(*(double*)entry->value);
 
2772
      item_type= Item::REAL_ITEM;
 
2773
      break;
 
2774
    case INT_RESULT:
 
2775
      set_int(*(longlong*)entry->value, MY_INT64_NUM_DECIMAL_DIGITS);
 
2776
      item_type= Item::INT_ITEM;
 
2777
      break;
 
2778
    case STRING_RESULT:
 
2779
    {
 
2780
      CHARSET_INFO *fromcs= entry->collation.collation;
 
2781
      CHARSET_INFO *tocs= thd->variables.collation_connection;
 
2782
      uint32 dummy_offset;
 
2783
 
 
2784
      value.cs_info.character_set_of_placeholder= fromcs;
 
2785
      value.cs_info.character_set_client= thd->variables.character_set_client;
 
2786
      /*
 
2787
        Setup source and destination character sets so that they
 
2788
        are different only if conversion is necessary: this will
 
2789
        make later checks easier.
 
2790
      */
 
2791
      value.cs_info.final_character_set_of_str_value=
 
2792
        String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
 
2793
        tocs : fromcs;
 
2794
      /*
 
2795
        Exact value of max_length is not known unless data is converted to
 
2796
        charset of connection, so we have to set it later.
 
2797
      */
 
2798
      item_type= Item::STRING_ITEM;
 
2799
 
 
2800
      if (set_str((const char *)entry->value, entry->length))
 
2801
        DBUG_RETURN(1);
 
2802
      break;
 
2803
    }
 
2804
    case DECIMAL_RESULT:
 
2805
    {
 
2806
      const my_decimal *ent_value= (const my_decimal *)entry->value;
 
2807
      my_decimal2decimal(ent_value, &decimal_value);
 
2808
      state= DECIMAL_VALUE;
 
2809
      decimals= ent_value->frac;
 
2810
      max_length=
 
2811
        my_decimal_precision_to_length_no_truncation(ent_value->precision(),
 
2812
                                                     decimals, unsigned_flag);
 
2813
      item_type= Item::DECIMAL_ITEM;
 
2814
      break;
 
2815
    }
 
2816
    default:
 
2817
      DBUG_ASSERT(0);
 
2818
      set_null();
 
2819
    }
 
2820
  }
 
2821
  else
 
2822
    set_null();
 
2823
 
 
2824
  DBUG_RETURN(0);
 
2825
}
 
2826
 
 
2827
/**
 
2828
  Resets parameter after execution.
 
2829
 
 
2830
  @note
 
2831
    We clear null_value here instead of setting it in set_* methods,
 
2832
    because we want more easily handle case for long data.
 
2833
*/
 
2834
 
 
2835
void Item_param::reset()
 
2836
{
 
2837
  DBUG_ENTER("Item_param::reset");
 
2838
  /* Shrink string buffer if it's bigger than max possible CHAR column */
 
2839
  if (str_value.alloced_length() > MAX_CHAR_WIDTH)
 
2840
    str_value.free();
 
2841
  else
 
2842
    str_value.length(0);
 
2843
  str_value_ptr.length(0);
 
2844
  /*
 
2845
    We must prevent all charset conversions until data has been written
 
2846
    to the binary log.
 
2847
  */
 
2848
  str_value.set_charset(&my_charset_bin);
 
2849
  collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
 
2850
  state= NO_VALUE;
 
2851
  maybe_null= 1;
 
2852
  null_value= 0;
 
2853
  /*
 
2854
    Don't reset item_type to PARAM_ITEM: it's only needed to guard
 
2855
    us from item optimizations at prepare stage, when item doesn't yet
 
2856
    contain a literal of some kind.
 
2857
    In all other cases when this object is accessed its value is
 
2858
    set (this assumption is guarded by 'state' and
 
2859
    DBUG_ASSERTS(state != NO_VALUE) in all Item_param::get_*
 
2860
    methods).
 
2861
  */
 
2862
  DBUG_VOID_RETURN;
 
2863
}
 
2864
 
 
2865
 
 
2866
int Item_param::save_in_field(Field *field, bool no_conversions)
 
2867
{
 
2868
  field->set_notnull();
 
2869
 
 
2870
  switch (state) {
 
2871
  case INT_VALUE:
 
2872
    return field->store(value.integer, unsigned_flag);
 
2873
  case REAL_VALUE:
 
2874
    return field->store(value.real);
 
2875
  case DECIMAL_VALUE:
 
2876
    return field->store_decimal(&decimal_value);
 
2877
  case TIME_VALUE:
 
2878
    field->store_time(&value.time, value.time.time_type);
 
2879
    return 0;
 
2880
  case STRING_VALUE:
 
2881
  case LONG_DATA_VALUE:
 
2882
    return field->store(str_value.ptr(), str_value.length(),
 
2883
                        str_value.charset());
 
2884
  case NULL_VALUE:
 
2885
    return set_field_to_null_with_conversions(field, no_conversions);
 
2886
  case NO_VALUE:
 
2887
  default:
 
2888
    DBUG_ASSERT(0);
 
2889
  }
 
2890
  return 1;
 
2891
}
 
2892
 
 
2893
 
 
2894
bool Item_param::get_time(MYSQL_TIME *res)
 
2895
{
 
2896
  if (state == TIME_VALUE)
 
2897
  {
 
2898
    *res= value.time;
 
2899
    return 0;
 
2900
  }
 
2901
  /*
 
2902
    If parameter value isn't supplied assertion will fire in val_str()
 
2903
    which is called from Item::get_time().
 
2904
  */
 
2905
  return Item::get_time(res);
 
2906
}
 
2907
 
 
2908
 
 
2909
bool Item_param::get_date(MYSQL_TIME *res, uint fuzzydate)
 
2910
{
 
2911
  if (state == TIME_VALUE)
 
2912
  {
 
2913
    *res= value.time;
 
2914
    return 0;
 
2915
  }
 
2916
  return Item::get_date(res, fuzzydate);
 
2917
}
 
2918
 
 
2919
 
 
2920
double Item_param::val_real()
 
2921
{
 
2922
  switch (state) {
 
2923
  case REAL_VALUE:
 
2924
    return value.real;
 
2925
  case INT_VALUE:
 
2926
    return (double) value.integer;
 
2927
  case DECIMAL_VALUE:
 
2928
  {
 
2929
    double result;
 
2930
    my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
 
2931
    return result;
 
2932
  }
 
2933
  case STRING_VALUE:
 
2934
  case LONG_DATA_VALUE:
 
2935
  {
 
2936
    int dummy_err;
 
2937
    char *end_not_used;
 
2938
    return my_strntod(str_value.charset(), (char*) str_value.ptr(),
 
2939
                      str_value.length(), &end_not_used, &dummy_err);
 
2940
  }
 
2941
  case TIME_VALUE:
 
2942
    /*
 
2943
      This works for example when user says SELECT ?+0.0 and supplies
 
2944
      time value for the placeholder.
 
2945
    */
 
2946
    return ulonglong2double(TIME_to_ulonglong(&value.time));
 
2947
  case NULL_VALUE:
 
2948
    return 0.0;
 
2949
  default:
 
2950
    DBUG_ASSERT(0);
 
2951
  }
 
2952
  return 0.0;
 
2953
 
2954
 
 
2955
 
 
2956
longlong Item_param::val_int() 
 
2957
 
2958
  switch (state) {
 
2959
  case REAL_VALUE:
 
2960
    return (longlong) rint(value.real);
 
2961
  case INT_VALUE:
 
2962
    return value.integer;
 
2963
  case DECIMAL_VALUE:
 
2964
  {
 
2965
    longlong i;
 
2966
    my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &i);
 
2967
    return i;
 
2968
  }
 
2969
  case STRING_VALUE:
 
2970
  case LONG_DATA_VALUE:
 
2971
    {
 
2972
      int dummy_err;
 
2973
      return my_strntoll(str_value.charset(), str_value.ptr(),
 
2974
                         str_value.length(), 10, (char**) 0, &dummy_err);
 
2975
    }
 
2976
  case TIME_VALUE:
 
2977
    return (longlong) TIME_to_ulonglong(&value.time);
 
2978
  case NULL_VALUE:
 
2979
    return 0; 
 
2980
  default:
 
2981
    DBUG_ASSERT(0);
 
2982
  }
 
2983
  return 0;
 
2984
}
 
2985
 
 
2986
 
 
2987
my_decimal *Item_param::val_decimal(my_decimal *dec)
 
2988
{
 
2989
  switch (state) {
 
2990
  case DECIMAL_VALUE:
 
2991
    return &decimal_value;
 
2992
  case REAL_VALUE:
 
2993
    double2my_decimal(E_DEC_FATAL_ERROR, value.real, dec);
 
2994
    return dec;
 
2995
  case INT_VALUE:
 
2996
    int2my_decimal(E_DEC_FATAL_ERROR, value.integer, unsigned_flag, dec);
 
2997
    return dec;
 
2998
  case STRING_VALUE:
 
2999
  case LONG_DATA_VALUE:
 
3000
    string2my_decimal(E_DEC_FATAL_ERROR, &str_value, dec);
 
3001
    return dec;
 
3002
  case TIME_VALUE:
 
3003
  {
 
3004
    longlong i= (longlong) TIME_to_ulonglong(&value.time);
 
3005
    int2my_decimal(E_DEC_FATAL_ERROR, i, 0, dec);
 
3006
    return dec;
 
3007
  }
 
3008
  case NULL_VALUE:
 
3009
    return 0; 
 
3010
  default:
 
3011
    DBUG_ASSERT(0);
 
3012
  }
 
3013
  return 0;
 
3014
}
 
3015
 
 
3016
 
 
3017
String *Item_param::val_str(String* str) 
 
3018
 
3019
  switch (state) {
 
3020
  case STRING_VALUE:
 
3021
  case LONG_DATA_VALUE:
 
3022
    return &str_value_ptr;
 
3023
  case REAL_VALUE:
 
3024
    str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
 
3025
    return str;
 
3026
  case INT_VALUE:
 
3027
    str->set(value.integer, &my_charset_bin);
 
3028
    return str;
 
3029
  case DECIMAL_VALUE:
 
3030
    if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
 
3031
                          0, 0, 0, str) <= 1)
 
3032
      return str;
 
3033
    return NULL;
 
3034
  case TIME_VALUE:
 
3035
  {
 
3036
    if (str->reserve(MAX_DATE_STRING_REP_LENGTH))
 
3037
      break;
 
3038
    str->length((uint) my_TIME_to_str(&value.time, (char*) str->ptr()));
 
3039
    str->set_charset(&my_charset_bin);
 
3040
    return str;
 
3041
  }
 
3042
  case NULL_VALUE:
 
3043
    return NULL; 
 
3044
  default:
 
3045
    DBUG_ASSERT(0);
 
3046
  }
 
3047
  return str;
 
3048
}
 
3049
 
 
3050
/**
 
3051
  Return Param item values in string format, for generating the dynamic 
 
3052
  query used in update/binary logs.
 
3053
 
 
3054
  @todo
 
3055
    - Change interface and implementation to fill log data in place
 
3056
    and avoid one more memcpy/alloc between str and log string.
 
3057
    - In case of error we need to notify replication
 
3058
    that binary log contains wrong statement 
 
3059
*/
 
3060
 
 
3061
const String *Item_param::query_val_str(String* str) const
 
3062
{
 
3063
  switch (state) {
 
3064
  case INT_VALUE:
 
3065
    str->set_int(value.integer, unsigned_flag, &my_charset_bin);
 
3066
    break;
 
3067
  case REAL_VALUE:
 
3068
    str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
 
3069
    break;
 
3070
  case DECIMAL_VALUE:
 
3071
    if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
 
3072
                          0, 0, 0, str) > 1)
 
3073
      return &my_null_string;
 
3074
    break;
 
3075
  case TIME_VALUE:
 
3076
    {
 
3077
      char *buf, *ptr;
 
3078
      str->length(0);
 
3079
      /*
 
3080
        TODO: in case of error we need to notify replication
 
3081
        that binary log contains wrong statement 
 
3082
      */
 
3083
      if (str->reserve(MAX_DATE_STRING_REP_LENGTH+3))
 
3084
        break; 
 
3085
 
 
3086
      /* Create date string inplace */
 
3087
      buf= str->c_ptr_quick();
 
3088
      ptr= buf;
 
3089
      *ptr++= '\'';
 
3090
      ptr+= (uint) my_TIME_to_str(&value.time, ptr);
 
3091
      *ptr++= '\'';
 
3092
      str->length((uint32) (ptr - buf));
 
3093
      break;
 
3094
    }
 
3095
  case STRING_VALUE:
 
3096
  case LONG_DATA_VALUE:
 
3097
    {
 
3098
      str->length(0);
 
3099
      append_query_string(value.cs_info.character_set_client, &str_value, str);
 
3100
      break;
 
3101
    }
 
3102
  case NULL_VALUE:
 
3103
    return &my_null_string;
 
3104
  default:
 
3105
    DBUG_ASSERT(0);
 
3106
  }
 
3107
  return str;
 
3108
}
 
3109
 
 
3110
 
 
3111
/**
 
3112
  Convert string from client character set to the character set of
 
3113
  connection.
 
3114
*/
 
3115
 
 
3116
bool Item_param::convert_str_value(THD *thd)
 
3117
{
 
3118
  bool rc= FALSE;
 
3119
  if (state == STRING_VALUE || state == LONG_DATA_VALUE)
 
3120
  {
 
3121
    /*
 
3122
      Check is so simple because all charsets were set up properly
 
3123
      in setup_one_conversion_function, where typecode of
 
3124
      placeholder was also taken into account: the variables are different
 
3125
      here only if conversion is really necessary.
 
3126
    */
 
3127
    if (value.cs_info.final_character_set_of_str_value !=
 
3128
        value.cs_info.character_set_of_placeholder)
 
3129
    {
 
3130
      rc= thd->convert_string(&str_value,
 
3131
                              value.cs_info.character_set_of_placeholder,
 
3132
                              value.cs_info.final_character_set_of_str_value);
 
3133
    }
 
3134
    else
 
3135
      str_value.set_charset(value.cs_info.final_character_set_of_str_value);
 
3136
    /* Here str_value is guaranteed to be in final_character_set_of_str_value */
 
3137
 
 
3138
    max_length= str_value.numchars() * str_value.charset()->mbmaxlen;
 
3139
    decimals= 0;
 
3140
    /*
 
3141
      str_value_ptr is returned from val_str(). It must be not alloced
 
3142
      to prevent it's modification by val_str() invoker.
 
3143
    */
 
3144
    str_value_ptr.set(str_value.ptr(), str_value.length(),
 
3145
                      str_value.charset());
 
3146
    /* Synchronize item charset with value charset */
 
3147
    collation.set(str_value.charset(), DERIVATION_COERCIBLE);
 
3148
  }
 
3149
  return rc;
 
3150
}
 
3151
 
 
3152
 
 
3153
bool Item_param::basic_const_item() const
 
3154
{
 
3155
  if (state == NO_VALUE || state == TIME_VALUE)
 
3156
    return FALSE;
 
3157
  return TRUE;
 
3158
}
 
3159
 
 
3160
 
 
3161
Item *
 
3162
Item_param::clone_item()
 
3163
{
 
3164
  /* see comments in the header file */
 
3165
  switch (state) {
 
3166
  case NULL_VALUE:
 
3167
    return new Item_null(name);
 
3168
  case INT_VALUE:
 
3169
    return (unsigned_flag ?
 
3170
            new Item_uint(name, value.integer, max_length) :
 
3171
            new Item_int(name, value.integer, max_length));
 
3172
  case REAL_VALUE:
 
3173
    return new Item_float(name, value.real, decimals, max_length);
 
3174
  case STRING_VALUE:
 
3175
  case LONG_DATA_VALUE:
 
3176
    return new Item_string(name, str_value.c_ptr_quick(), str_value.length(),
 
3177
                           str_value.charset());
 
3178
  case TIME_VALUE:
 
3179
    break;
 
3180
  case NO_VALUE:
 
3181
  default:
 
3182
    DBUG_ASSERT(0);
 
3183
  };
 
3184
  return 0;
 
3185
}
 
3186
 
 
3187
 
 
3188
bool
 
3189
Item_param::eq(const Item *arg, bool binary_cmp) const
 
3190
{
 
3191
  Item *item;
 
3192
  if (!basic_const_item() || !arg->basic_const_item() || arg->type() != type())
 
3193
    return FALSE;
 
3194
  /*
 
3195
    We need to cast off const to call val_int(). This should be OK for
 
3196
    a basic constant.
 
3197
  */
 
3198
  item= (Item*) arg;
 
3199
 
 
3200
  switch (state) {
 
3201
  case NULL_VALUE:
 
3202
    return TRUE;
 
3203
  case INT_VALUE:
 
3204
    return value.integer == item->val_int() &&
 
3205
           unsigned_flag == item->unsigned_flag;
 
3206
  case REAL_VALUE:
 
3207
    return value.real == item->val_real();
 
3208
  case STRING_VALUE:
 
3209
  case LONG_DATA_VALUE:
 
3210
    if (binary_cmp)
 
3211
      return !stringcmp(&str_value, &item->str_value);
 
3212
    return !sortcmp(&str_value, &item->str_value, collation.collation);
 
3213
  default:
 
3214
    break;
 
3215
  }
 
3216
  return FALSE;
 
3217
}
 
3218
 
 
3219
/* End of Item_param related */
 
3220
 
 
3221
void Item_param::print(String *str, enum_query_type query_type)
 
3222
{
 
3223
  if (state == NO_VALUE)
 
3224
  {
 
3225
    str->append('?');
 
3226
  }
 
3227
  else
 
3228
  {
 
3229
    char buffer[STRING_BUFFER_USUAL_SIZE];
 
3230
    String tmp(buffer, sizeof(buffer), &my_charset_bin);
 
3231
    const String *res;
 
3232
    res= query_val_str(&tmp);
 
3233
    str->append(*res);
 
3234
  }
 
3235
}
 
3236
 
 
3237
 
 
3238
/**
 
3239
  Preserve the original parameter types and values
 
3240
  when re-preparing a prepared statement.
 
3241
 
 
3242
  @details Copy parameter type information and conversion
 
3243
  function pointers from a parameter of the old statement
 
3244
  to the corresponding parameter of the new one.
 
3245
 
 
3246
  Move parameter values from the old parameters to the new
 
3247
  one. We simply "exchange" the values, which allows
 
3248
  to save on allocation and character set conversion in
 
3249
  case a parameter is a string or a blob/clob.
 
3250
 
 
3251
  The old parameter gets the value of this one, which
 
3252
  ensures that all memory of this parameter is freed
 
3253
  correctly.
 
3254
 
 
3255
  @param[in]  src   parameter item of the original
 
3256
                    prepared statement
 
3257
*/
 
3258
 
 
3259
void
 
3260
Item_param::set_param_type_and_swap_value(Item_param *src)
 
3261
{
 
3262
  unsigned_flag= src->unsigned_flag;
 
3263
  param_type= src->param_type;
 
3264
  set_param_func= src->set_param_func;
 
3265
  item_type= src->item_type;
 
3266
  item_result_type= src->item_result_type;
 
3267
 
 
3268
  collation.set(src->collation);
 
3269
  maybe_null= src->maybe_null;
 
3270
  null_value= src->null_value;
 
3271
  max_length= src->max_length;
 
3272
  decimals= src->decimals;
 
3273
  state= src->state;
 
3274
  value= src->value;
 
3275
 
 
3276
  decimal_value.swap(src->decimal_value);
 
3277
  str_value.swap(src->str_value);
 
3278
  str_value_ptr.swap(src->str_value_ptr);
 
3279
}
 
3280
 
 
3281
/****************************************************************************
 
3282
  Item_copy
 
3283
****************************************************************************/
 
3284
Item_copy *Item_copy::create (Item *item)
 
3285
{
 
3286
  switch (item->result_type())
 
3287
  {
 
3288
    case STRING_RESULT:
 
3289
      return new Item_copy_string (item);
 
3290
    case REAL_RESULT: 
 
3291
      return new Item_copy_float (item);
 
3292
    case INT_RESULT:
 
3293
      return item->unsigned_flag ? 
 
3294
        new Item_copy_uint (item) : new Item_copy_int (item);
 
3295
    case DECIMAL_RESULT:
 
3296
      return new Item_copy_decimal (item);
 
3297
    default:
 
3298
      DBUG_ASSERT (0);
 
3299
  }
 
3300
  /* should not happen */
 
3301
  return NULL;
 
3302
}
 
3303
 
 
3304
/****************************************************************************
 
3305
  Item_copy_string
 
3306
****************************************************************************/
 
3307
 
 
3308
double Item_copy_string::val_real()
 
3309
{
 
3310
  int err_not_used;
 
3311
  char *end_not_used;
 
3312
  return (null_value ? 0.0 :
 
3313
          my_strntod(str_value.charset(), (char*) str_value.ptr(),
 
3314
                     str_value.length(), &end_not_used, &err_not_used));
 
3315
}
 
3316
 
 
3317
longlong Item_copy_string::val_int()
 
3318
{
 
3319
  int err;
 
3320
  return null_value ? LL(0) : my_strntoll(str_value.charset(),str_value.ptr(),
 
3321
                                          str_value.length(),10, (char**) 0,
 
3322
                                          &err); 
 
3323
}
 
3324
 
 
3325
 
 
3326
int Item_copy_string::save_in_field(Field *field, bool no_conversions)
 
3327
{
 
3328
  return save_str_value_in_field(field, &str_value);
 
3329
}
 
3330
 
 
3331
 
 
3332
void Item_copy_string::copy()
 
3333
{
 
3334
  String *res=item->val_str(&str_value);
 
3335
  if (res && res != &str_value)
 
3336
    str_value.copy(*res);
 
3337
  null_value=item->null_value;
 
3338
}
 
3339
 
 
3340
/* ARGSUSED */
 
3341
String *Item_copy_string::val_str(String *str)
 
3342
{
 
3343
  // Item_copy_string is used without fix_fields call
 
3344
  if (null_value)
 
3345
    return (String*) 0;
 
3346
  return &str_value;
 
3347
}
 
3348
 
 
3349
 
 
3350
my_decimal *Item_copy_string::val_decimal(my_decimal *decimal_value)
 
3351
{
 
3352
  // Item_copy_string is used without fix_fields call
 
3353
  if (null_value)
 
3354
    return (my_decimal *) 0;
 
3355
  string2my_decimal(E_DEC_FATAL_ERROR, &str_value, decimal_value);
 
3356
  return (decimal_value);
 
3357
}
 
3358
 
 
3359
 
 
3360
/****************************************************************************
 
3361
  Item_copy_int
 
3362
****************************************************************************/
 
3363
 
 
3364
void Item_copy_int::copy()
 
3365
{
 
3366
  cached_value= item->val_int();
 
3367
  null_value=item->null_value;
 
3368
}
 
3369
 
 
3370
static int save_int_value_in_field (Field *field, longlong nr, 
 
3371
                                    bool null_value, bool unsigned_flag);
 
3372
 
 
3373
int Item_copy_int::save_in_field(Field *field, bool no_conversions)
 
3374
{
 
3375
  return save_int_value_in_field(field, cached_value, 
 
3376
                                 null_value, unsigned_flag);
 
3377
}
 
3378
 
 
3379
 
 
3380
String *Item_copy_int::val_str(String *str)
 
3381
{
 
3382
  if (null_value)
 
3383
    return (String *) 0;
 
3384
 
 
3385
  str->set(cached_value, &my_charset_bin);
 
3386
  return str;
 
3387
}
 
3388
 
 
3389
 
 
3390
my_decimal *Item_copy_int::val_decimal(my_decimal *decimal_value)
 
3391
{
 
3392
  if (null_value)
 
3393
    return (my_decimal *) 0;
 
3394
 
 
3395
  int2my_decimal(E_DEC_FATAL_ERROR, cached_value, unsigned_flag, decimal_value);
 
3396
  return decimal_value;
 
3397
}
 
3398
 
 
3399
 
 
3400
/****************************************************************************
 
3401
  Item_copy_uint
 
3402
****************************************************************************/
 
3403
 
 
3404
String *Item_copy_uint::val_str(String *str)
 
3405
{
 
3406
  if (null_value)
 
3407
    return (String *) 0;
 
3408
 
 
3409
  str->set((ulonglong) cached_value, &my_charset_bin);
 
3410
  return str;
 
3411
}
 
3412
 
 
3413
 
 
3414
/****************************************************************************
 
3415
  Item_copy_float
 
3416
****************************************************************************/
 
3417
 
 
3418
String *Item_copy_float::val_str(String *str)
 
3419
{
 
3420
  if (null_value)
 
3421
    return (String *) 0;
 
3422
  else
 
3423
  {
 
3424
    double nr= val_real();
 
3425
    str->set_real(nr,decimals, &my_charset_bin);
 
3426
    return str;
 
3427
  }
 
3428
}
 
3429
 
 
3430
 
 
3431
my_decimal *Item_copy_float::val_decimal(my_decimal *decimal_value)
 
3432
{
 
3433
  if (null_value)
 
3434
    return (my_decimal *) 0;
 
3435
  else
 
3436
  {
 
3437
    double nr= val_real();
 
3438
    double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
 
3439
    return decimal_value;
 
3440
  }
 
3441
}
 
3442
 
 
3443
 
 
3444
int Item_copy_float::save_in_field(Field *field, bool no_conversions)
 
3445
{
 
3446
  if (null_value)
 
3447
    return set_field_to_null(field);
 
3448
  field->set_notnull();
 
3449
  return field->store(cached_value);
 
3450
}
 
3451
 
 
3452
 
 
3453
/****************************************************************************
 
3454
  Item_copy_decimal
 
3455
****************************************************************************/
 
3456
 
 
3457
int Item_copy_decimal::save_in_field(Field *field, bool no_conversions)
 
3458
{
 
3459
  if (null_value)
 
3460
    return set_field_to_null(field);
 
3461
  field->set_notnull();
 
3462
  return field->store_decimal(&cached_value);
 
3463
}
 
3464
 
 
3465
 
 
3466
String *Item_copy_decimal::val_str(String *result)
 
3467
{
 
3468
  if (null_value)
 
3469
    return (String *) 0;
 
3470
  result->set_charset(&my_charset_bin);
 
3471
  my_decimal2string(E_DEC_FATAL_ERROR, &cached_value, 0, 0, 0, result);
 
3472
  return result;
 
3473
}
 
3474
 
 
3475
 
 
3476
double Item_copy_decimal::val_real()
 
3477
{
 
3478
  if (null_value)
 
3479
    return 0.0;
 
3480
  else
 
3481
  {
 
3482
    double result;
 
3483
    my_decimal2double(E_DEC_FATAL_ERROR, &cached_value, &result);
 
3484
    return result;
 
3485
  }
 
3486
}
 
3487
 
 
3488
 
 
3489
longlong Item_copy_decimal::val_int()
 
3490
{
 
3491
  if (null_value)
 
3492
    return LL(0);
 
3493
  else
 
3494
  {
 
3495
    longlong result;
 
3496
    my_decimal2int(E_DEC_FATAL_ERROR, &cached_value, unsigned_flag, &result);
 
3497
    return result;
 
3498
  }
 
3499
}
 
3500
 
 
3501
 
 
3502
void Item_copy_decimal::copy()
 
3503
{
 
3504
  my_decimal *nr= item->val_decimal(&cached_value);
 
3505
  if (nr && nr != &cached_value)
 
3506
    memcpy (&cached_value, nr, sizeof (my_decimal)); 
 
3507
  null_value= item->null_value;
 
3508
}
 
3509
 
 
3510
 
 
3511
/*
 
3512
  Functions to convert item to field (for send_fields)
 
3513
*/
 
3514
 
 
3515
/* ARGSUSED */
 
3516
bool Item::fix_fields(THD *thd, Item **ref)
 
3517
{
 
3518
 
 
3519
  // We do not check fields which are fixed during construction
 
3520
  DBUG_ASSERT(fixed == 0 || basic_const_item());
 
3521
  fixed= 1;
 
3522
  return FALSE;
 
3523
}
 
3524
 
 
3525
double Item_ref_null_helper::val_real()
 
3526
{
 
3527
  DBUG_ASSERT(fixed == 1);
 
3528
  double tmp= (*ref)->val_result();
 
3529
  owner->was_null|= null_value= (*ref)->null_value;
 
3530
  return tmp;
 
3531
}
 
3532
 
 
3533
 
 
3534
longlong Item_ref_null_helper::val_int()
 
3535
{
 
3536
  DBUG_ASSERT(fixed == 1);
 
3537
  longlong tmp= (*ref)->val_int_result();
 
3538
  owner->was_null|= null_value= (*ref)->null_value;
 
3539
  return tmp;
 
3540
}
 
3541
 
 
3542
 
 
3543
my_decimal *Item_ref_null_helper::val_decimal(my_decimal *decimal_value)
 
3544
{
 
3545
  DBUG_ASSERT(fixed == 1);
 
3546
  my_decimal *val= (*ref)->val_decimal_result(decimal_value);
 
3547
  owner->was_null|= null_value= (*ref)->null_value;
 
3548
  return val;
 
3549
}
 
3550
 
 
3551
 
 
3552
bool Item_ref_null_helper::val_bool()
 
3553
{
 
3554
  DBUG_ASSERT(fixed == 1);
 
3555
  bool val= (*ref)->val_bool_result();
 
3556
  owner->was_null|= null_value= (*ref)->null_value;
 
3557
  return val;
 
3558
}
 
3559
 
 
3560
 
 
3561
String* Item_ref_null_helper::val_str(String* s)
 
3562
{
 
3563
  DBUG_ASSERT(fixed == 1);
 
3564
  String* tmp= (*ref)->str_result(s);
 
3565
  owner->was_null|= null_value= (*ref)->null_value;
 
3566
  return tmp;
 
3567
}
 
3568
 
 
3569
 
 
3570
bool Item_ref_null_helper::get_date(MYSQL_TIME *ltime, uint fuzzydate)
 
3571
{  
 
3572
  return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate));
 
3573
}
 
3574
 
 
3575
 
 
3576
/**
 
3577
  Mark item and SELECT_LEXs as dependent if item was resolved in
 
3578
  outer SELECT.
 
3579
 
 
3580
  @param thd             thread handler
 
3581
  @param last            select from which current item depend
 
3582
  @param current         current select
 
3583
  @param resolved_item   item which was resolved in outer SELECT(for warning)
 
3584
  @param mark_item       item which should be marked (can be differ in case of
 
3585
                         substitution)
 
3586
*/
 
3587
 
 
3588
static void mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current,
 
3589
                              Item_ident *resolved_item,
 
3590
                              Item_ident *mark_item)
 
3591
{
 
3592
  const char *db_name= (resolved_item->db_name ?
 
3593
                        resolved_item->db_name : "");
 
3594
  const char *table_name= (resolved_item->table_name ?
 
3595
                           resolved_item->table_name : "");
 
3596
  /* store pointer on SELECT_LEX from which item is dependent */
 
3597
  if (mark_item)
 
3598
    mark_item->depended_from= last;
 
3599
  current->mark_as_dependent(last);
 
3600
  if (thd->lex->describe & DESCRIBE_EXTENDED)
 
3601
  {
 
3602
    push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
 
3603
                 ER_WARN_FIELD_RESOLVED, ER(ER_WARN_FIELD_RESOLVED),
 
3604
                 db_name, (db_name[0] ? "." : ""),
 
3605
                 table_name, (table_name [0] ? "." : ""),
 
3606
                 resolved_item->field_name,
 
3607
                 current->select_number, last->select_number);
 
3608
  }
 
3609
}
 
3610
 
 
3611
 
 
3612
/**
 
3613
  Mark range of selects and resolved identifier (field/reference)
 
3614
  item as dependent.
 
3615
 
 
3616
  @param thd             thread handler
 
3617
  @param last_select     select where resolved_item was resolved
 
3618
  @param current_sel     current select (select where resolved_item was placed)
 
3619
  @param found_field     field which was found during resolving
 
3620
  @param found_item      Item which was found during resolving (if resolved
 
3621
                         identifier belongs to VIEW)
 
3622
  @param resolved_item   Identifier which was resolved
 
3623
 
 
3624
  @note
 
3625
    We have to mark all items between current_sel (including) and
 
3626
    last_select (excluding) as dependend (select before last_select should
 
3627
    be marked with actual table mask used by resolved item, all other with
 
3628
    OUTER_REF_TABLE_BIT) and also write dependence information to Item of
 
3629
    resolved identifier.
 
3630
*/
 
3631
 
 
3632
void mark_select_range_as_dependent(THD *thd,
 
3633
                                    SELECT_LEX *last_select,
 
3634
                                    SELECT_LEX *current_sel,
 
3635
                                    Field *found_field, Item *found_item,
 
3636
                                    Item_ident *resolved_item)
 
3637
{
 
3638
  /*
 
3639
    Go from current SELECT to SELECT where field was resolved (it
 
3640
    have to be reachable from current SELECT, because it was already
 
3641
    done once when we resolved this field and cached result of
 
3642
    resolving)
 
3643
  */
 
3644
  SELECT_LEX *previous_select= current_sel;
 
3645
  for (; previous_select->outer_select() != last_select;
 
3646
       previous_select= previous_select->outer_select())
 
3647
  {
 
3648
    Item_subselect *prev_subselect_item=
 
3649
      previous_select->master_unit()->item;
 
3650
    prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
 
3651
    prev_subselect_item->const_item_cache= 0;
 
3652
  }
 
3653
  {
 
3654
    Item_subselect *prev_subselect_item=
 
3655
      previous_select->master_unit()->item;
 
3656
    Item_ident *dependent= resolved_item;
 
3657
    if (found_field == view_ref_found)
 
3658
    {
 
3659
      Item::Type type= found_item->type();
 
3660
      prev_subselect_item->used_tables_cache|=
 
3661
        found_item->used_tables();
 
3662
      dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
 
3663
                  (Item_ident*) found_item :
 
3664
                  0);
 
3665
    }
 
3666
    else
 
3667
      prev_subselect_item->used_tables_cache|=
 
3668
        found_field->table->map;
 
3669
    prev_subselect_item->const_item_cache= 0;
 
3670
    mark_as_dependent(thd, last_select, current_sel, resolved_item,
 
3671
                      dependent);
 
3672
  }
 
3673
}
 
3674
 
 
3675
 
 
3676
/**
 
3677
  Search a GROUP BY clause for a field with a certain name.
 
3678
 
 
3679
  Search the GROUP BY list for a column named as find_item. When searching
 
3680
  preference is given to columns that are qualified with the same table (and
 
3681
  database) name as the one being searched for.
 
3682
 
 
3683
  @param find_item     the item being searched for
 
3684
  @param group_list    GROUP BY clause
 
3685
 
 
3686
  @return
 
3687
    - the found item on success
 
3688
    - NULL if find_item is not in group_list
 
3689
*/
 
3690
 
 
3691
static Item** find_field_in_group_list(Item *find_item, ORDER *group_list)
 
3692
{
 
3693
  const char *db_name;
 
3694
  const char *table_name;
 
3695
  const char *field_name;
 
3696
  ORDER      *found_group= NULL;
 
3697
  int         found_match_degree= 0;
 
3698
  Item_ident *cur_field;
 
3699
  int         cur_match_degree= 0;
 
3700
  char        name_buff[NAME_LEN+1];
 
3701
 
 
3702
  if (find_item->type() == Item::FIELD_ITEM ||
 
3703
      find_item->type() == Item::REF_ITEM)
 
3704
  {
 
3705
    db_name=    ((Item_ident*) find_item)->db_name;
 
3706
    table_name= ((Item_ident*) find_item)->table_name;
 
3707
    field_name= ((Item_ident*) find_item)->field_name;
 
3708
  }
 
3709
  else
 
3710
    return NULL;
 
3711
 
 
3712
  if (db_name && lower_case_table_names)
 
3713
  {
 
3714
    /* Convert database to lower case for comparison */
 
3715
    strmake(name_buff, db_name, sizeof(name_buff)-1);
 
3716
    my_casedn_str(files_charset_info, name_buff);
 
3717
    db_name= name_buff;
 
3718
  }
 
3719
 
 
3720
  DBUG_ASSERT(field_name != 0);
 
3721
 
 
3722
  for (ORDER *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
 
3723
  {
 
3724
    if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM)
 
3725
    {
 
3726
      cur_field= (Item_ident*) *cur_group->item;
 
3727
      cur_match_degree= 0;
 
3728
      
 
3729
      DBUG_ASSERT(cur_field->field_name != 0);
 
3730
 
 
3731
      if (!my_strcasecmp(system_charset_info,
 
3732
                         cur_field->field_name, field_name))
 
3733
        ++cur_match_degree;
 
3734
      else
 
3735
        continue;
 
3736
 
 
3737
      if (cur_field->table_name && table_name)
 
3738
      {
 
3739
        /* If field_name is qualified by a table name. */
 
3740
        if (my_strcasecmp(table_alias_charset, cur_field->table_name, table_name))
 
3741
          /* Same field names, different tables. */
 
3742
          return NULL;
 
3743
 
 
3744
        ++cur_match_degree;
 
3745
        if (cur_field->db_name && db_name)
 
3746
        {
 
3747
          /* If field_name is also qualified by a database name. */
 
3748
          if (strcmp(cur_field->db_name, db_name))
 
3749
            /* Same field names, different databases. */
 
3750
            return NULL;
 
3751
          ++cur_match_degree;
 
3752
        }
 
3753
      }
 
3754
 
 
3755
      if (cur_match_degree > found_match_degree)
 
3756
      {
 
3757
        found_match_degree= cur_match_degree;
 
3758
        found_group= cur_group;
 
3759
      }
 
3760
      else if (found_group && (cur_match_degree == found_match_degree) &&
 
3761
               ! (*(found_group->item))->eq(cur_field, 0))
 
3762
      {
 
3763
        /*
 
3764
          If the current resolve candidate matches equally well as the current
 
3765
          best match, they must reference the same column, otherwise the field
 
3766
          is ambiguous.
 
3767
        */
 
3768
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
 
3769
                 find_item->full_name(), current_thd->where);
 
3770
        return NULL;
 
3771
      }
 
3772
    }
 
3773
  }
 
3774
 
 
3775
  if (found_group)
 
3776
    return found_group->item;
 
3777
  else
 
3778
    return NULL;
 
3779
}
 
3780
 
 
3781
 
 
3782
/**
 
3783
  Resolve a column reference in a sub-select.
 
3784
 
 
3785
  Resolve a column reference (usually inside a HAVING clause) against the
 
3786
  SELECT and GROUP BY clauses of the query described by 'select'. The name
 
3787
  resolution algorithm searches both the SELECT and GROUP BY clauses, and in
 
3788
  case of a name conflict prefers GROUP BY column names over SELECT names. If
 
3789
  both clauses contain different fields with the same names, a warning is
 
3790
  issued that name of 'ref' is ambiguous. We extend ANSI SQL in that when no
 
3791
  GROUP BY column is found, then a HAVING name is resolved as a possibly
 
3792
  derived SELECT column. This extension is allowed only if the
 
3793
  MODE_ONLY_FULL_GROUP_BY sql mode isn't enabled.
 
3794
 
 
3795
  @param thd     current thread
 
3796
  @param ref     column reference being resolved
 
3797
  @param select  the select that ref is resolved against
 
3798
 
 
3799
  @note
 
3800
    The resolution procedure is:
 
3801
    - Search for a column or derived column named col_ref_i [in table T_j]
 
3802
    in the SELECT clause of Q.
 
3803
    - Search for a column named col_ref_i [in table T_j]
 
3804
    in the GROUP BY clause of Q.
 
3805
    - If found different columns with the same name in GROUP BY and SELECT
 
3806
    - issue a warning and return the GROUP BY column,
 
3807
    - otherwise
 
3808
    - if the MODE_ONLY_FULL_GROUP_BY mode is enabled return error
 
3809
    - else return the found SELECT column.
 
3810
 
 
3811
 
 
3812
  @return
 
3813
    - NULL - there was an error, and the error was already reported
 
3814
    - not_found_item - the item was not resolved, no error was reported
 
3815
    - resolved item - if the item was resolved
 
3816
*/
 
3817
 
 
3818
static Item**
 
3819
resolve_ref_in_select_and_group(THD *thd, Item_ident *ref, SELECT_LEX *select)
 
3820
{
 
3821
  Item **group_by_ref= NULL;
 
3822
  Item **select_ref= NULL;
 
3823
  ORDER *group_list= (ORDER*) select->group_list.first;
 
3824
  bool ambiguous_fields= FALSE;
 
3825
  uint counter;
 
3826
  enum_resolution_type resolution;
 
3827
 
 
3828
  /*
 
3829
    Search for a column or derived column named as 'ref' in the SELECT
 
3830
    clause of the current select.
 
3831
  */
 
3832
  if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()),
 
3833
                                      &counter, REPORT_EXCEPT_NOT_FOUND,
 
3834
                                      &resolution)))
 
3835
    return NULL; /* Some error occurred. */
 
3836
  if (resolution == RESOLVED_AGAINST_ALIAS)
 
3837
    ref->alias_name_used= TRUE;
 
3838
 
 
3839
  /* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
 
3840
  if (select->having_fix_field && !ref->with_sum_func && group_list)
 
3841
  {
 
3842
    group_by_ref= find_field_in_group_list(ref, group_list);
 
3843
    
 
3844
    /* Check if the fields found in SELECT and GROUP BY are the same field. */
 
3845
    if (group_by_ref && (select_ref != not_found_item) &&
 
3846
        !((*group_by_ref)->eq(*select_ref, 0)))
 
3847
    {
 
3848
      ambiguous_fields= TRUE;
 
3849
      push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
 
3850
                          ER(ER_NON_UNIQ_ERROR), ref->full_name(),
 
3851
                          current_thd->where);
 
3852
 
 
3853
    }
 
3854
  }
 
3855
 
 
3856
  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
 
3857
      select->having_fix_field  &&
 
3858
      select_ref != not_found_item && !group_by_ref)
 
3859
  {
 
3860
    /*
 
3861
      Report the error if fields was found only in the SELECT item list and
 
3862
      the strict mode is enabled.
 
3863
    */
 
3864
    my_error(ER_NON_GROUPING_FIELD_USED, MYF(0),
 
3865
             ref->name, "HAVING");
 
3866
    return NULL;
 
3867
  }
 
3868
  if (select_ref != not_found_item || group_by_ref)
 
3869
  {
 
3870
    if (select_ref != not_found_item && !ambiguous_fields)
 
3871
    {
 
3872
      DBUG_ASSERT(*select_ref != 0);
 
3873
      if (!select->ref_pointer_array[counter])
 
3874
      {
 
3875
        my_error(ER_ILLEGAL_REFERENCE, MYF(0),
 
3876
                 ref->name, "forward reference in item list");
 
3877
        return NULL;
 
3878
      }
 
3879
      DBUG_ASSERT((*select_ref)->fixed);
 
3880
      return (select->ref_pointer_array + counter);
 
3881
    }
 
3882
    if (group_by_ref)
 
3883
      return group_by_ref;
 
3884
    DBUG_ASSERT(FALSE);
 
3885
    return NULL; /* So there is no compiler warning. */
 
3886
  }
 
3887
 
 
3888
  return (Item**) not_found_item;
 
3889
}
 
3890
 
 
3891
 
 
3892
/**
 
3893
  Resolve the name of an outer select column reference.
 
3894
 
 
3895
  The method resolves the column reference represented by 'this' as a column
 
3896
  present in outer selects that contain current select.
 
3897
 
 
3898
  In prepared statements, because of cache, find_field_in_tables()
 
3899
  can resolve fields even if they don't belong to current context.
 
3900
  In this case this method only finds appropriate context and marks
 
3901
  current select as dependent. The found reference of field should be
 
3902
  provided in 'from_field'.
 
3903
 
 
3904
  @param[in] thd             current thread
 
3905
  @param[in,out] from_field  found field reference or (Field*)not_found_field
 
3906
  @param[in,out] reference   view column if this item was resolved to a
 
3907
    view column
 
3908
 
 
3909
  @note
 
3910
    This is the inner loop of Item_field::fix_fields:
 
3911
  @code
 
3912
        for each outer query Q_k beginning from the inner-most one
 
3913
        {
 
3914
          search for a column or derived column named col_ref_i
 
3915
          [in table T_j] in the FROM clause of Q_k;
 
3916
 
 
3917
          if such a column is not found
 
3918
            Search for a column or derived column named col_ref_i
 
3919
            [in table T_j] in the SELECT and GROUP clauses of Q_k.
 
3920
        }
 
3921
  @endcode
 
3922
 
 
3923
  @retval
 
3924
    1   column succefully resolved and fix_fields() should continue.
 
3925
  @retval
 
3926
    0   column fully fixed and fix_fields() should return FALSE
 
3927
  @retval
 
3928
    -1  error occured
 
3929
*/
 
3930
 
 
3931
int
 
3932
Item_field::fix_outer_field(THD *thd, Field **from_field, Item **reference)
 
3933
{
 
3934
  enum_parsing_place place= NO_MATTER;
 
3935
  bool field_found= (*from_field != not_found_field);
 
3936
  bool upward_lookup= FALSE;
 
3937
 
 
3938
  /*
 
3939
    If there are outer contexts (outer selects, but current select is
 
3940
    not derived table or view) try to resolve this reference in the
 
3941
    outer contexts.
 
3942
 
 
3943
    We treat each subselect as a separate namespace, so that different
 
3944
    subselects may contain columns with the same names. The subselects
 
3945
    are searched starting from the innermost.
 
3946
  */
 
3947
  Name_resolution_context *last_checked_context= context;
 
3948
  Item **ref= (Item **) not_found_item;
 
3949
  SELECT_LEX *current_sel= (SELECT_LEX *) thd->lex->current_select;
 
3950
  Name_resolution_context *outer_context= 0;
 
3951
  SELECT_LEX *select= 0;
 
3952
  /* Currently derived tables cannot be correlated */
 
3953
  if (current_sel->master_unit()->first_select()->linkage !=
 
3954
      DERIVED_TABLE_TYPE)
 
3955
    outer_context= context->outer_context;
 
3956
  for (;
 
3957
       outer_context;
 
3958
       outer_context= outer_context->outer_context)
 
3959
  {
 
3960
    select= outer_context->select_lex;
 
3961
    Item_subselect *prev_subselect_item=
 
3962
      last_checked_context->select_lex->master_unit()->item;
 
3963
    last_checked_context= outer_context;
 
3964
    upward_lookup= TRUE;
 
3965
 
 
3966
    place= prev_subselect_item->parsing_place;
 
3967
    /*
 
3968
      If outer_field is set, field was already found by first call
 
3969
      to find_field_in_tables(). Only need to find appropriate context.
 
3970
    */
 
3971
    if (field_found && outer_context->select_lex !=
 
3972
        cached_table->select_lex)
 
3973
      continue;
 
3974
    /*
 
3975
      In case of a view, find_field_in_tables() writes the pointer to
 
3976
      the found view field into '*reference', in other words, it
 
3977
      substitutes this Item_field with the found expression.
 
3978
    */
 
3979
    if (field_found || (*from_field= find_field_in_tables(thd, this,
 
3980
                                          outer_context->
 
3981
                                            first_name_resolution_table,
 
3982
                                          outer_context->
 
3983
                                            last_name_resolution_table,
 
3984
                                          reference,
 
3985
                                          IGNORE_EXCEPT_NON_UNIQUE,
 
3986
                                          TRUE, TRUE)) !=
 
3987
        not_found_field)
 
3988
    {
 
3989
      if (*from_field)
 
3990
      {
 
3991
        if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
 
3992
            select->cur_pos_in_select_list != UNDEF_POS)
 
3993
        {
 
3994
          /*
 
3995
            As this is an outer field it should be added to the list of
 
3996
            non aggregated fields of the outer select.
 
3997
          */
 
3998
          marker= select->cur_pos_in_select_list;
 
3999
          select->non_agg_fields.push_back(this);
 
4000
        }
 
4001
        if (*from_field != view_ref_found)
 
4002
        {
 
4003
          prev_subselect_item->used_tables_cache|= (*from_field)->table->map;
 
4004
          prev_subselect_item->const_item_cache= 0;
 
4005
          set_field(*from_field);
 
4006
          if (!last_checked_context->select_lex->having_fix_field &&
 
4007
              select->group_list.elements &&
 
4008
              (place == SELECT_LIST || place == IN_HAVING))
 
4009
          {
 
4010
            Item_outer_ref *rf;
 
4011
            /*
 
4012
              If an outer field is resolved in a grouping select then it
 
4013
              is replaced for an Item_outer_ref object. Otherwise an
 
4014
              Item_field object is used.
 
4015
              The new Item_outer_ref object is saved in the inner_refs_list of
 
4016
              the outer select. Here it is only created. It can be fixed only
 
4017
              after the original field has been fixed and this is done in the
 
4018
              fix_inner_refs() function.
 
4019
            */
 
4020
            ;
 
4021
            if (!(rf= new Item_outer_ref(context, this)))
 
4022
              return -1;
 
4023
            thd->change_item_tree(reference, rf);
 
4024
            select->inner_refs_list.push_back(rf);
 
4025
            rf->in_sum_func= thd->lex->in_sum_func;
 
4026
          }
 
4027
          /*
 
4028
            A reference is resolved to a nest level that's outer or the same as
 
4029
            the nest level of the enclosing set function : adjust the value of
 
4030
            max_arg_level for the function if it's needed.
 
4031
          */
 
4032
          if (thd->lex->in_sum_func &&
 
4033
              thd->lex->in_sum_func->nest_level >= select->nest_level)
 
4034
          {
 
4035
            Item::Type ref_type= (*reference)->type();
 
4036
            set_if_bigger(thd->lex->in_sum_func->max_arg_level,
 
4037
                          select->nest_level);
 
4038
            set_field(*from_field);
 
4039
            fixed= 1;
 
4040
            mark_as_dependent(thd, last_checked_context->select_lex,
 
4041
                              context->select_lex, this,
 
4042
                              ((ref_type == REF_ITEM ||
 
4043
                                ref_type == FIELD_ITEM) ?
 
4044
                               (Item_ident*) (*reference) : 0));
 
4045
            return 0;
 
4046
          }
 
4047
        }
 
4048
        else
 
4049
        {
 
4050
          Item::Type ref_type= (*reference)->type();
 
4051
          prev_subselect_item->used_tables_cache|=
 
4052
            (*reference)->used_tables();
 
4053
          prev_subselect_item->const_item_cache&=
 
4054
            (*reference)->const_item();
 
4055
          mark_as_dependent(thd, last_checked_context->select_lex,
 
4056
                            context->select_lex, this,
 
4057
                            ((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ?
 
4058
                             (Item_ident*) (*reference) :
 
4059
                             0));
 
4060
          /*
 
4061
            A reference to a view field had been found and we
 
4062
            substituted it instead of this Item (find_field_in_tables
 
4063
            does it by assigning the new value to *reference), so now
 
4064
            we can return from this function.
 
4065
          */
 
4066
          return 0;
 
4067
        }
 
4068
      }
 
4069
      break;
 
4070
    }
 
4071
 
 
4072
    /* Search in SELECT and GROUP lists of the outer select. */
 
4073
    if (place != IN_WHERE && place != IN_ON)
 
4074
    {
 
4075
      if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
 
4076
        return -1; /* Some error occurred (e.g. ambiguous names). */
 
4077
      if (ref != not_found_item)
 
4078
      {
 
4079
        DBUG_ASSERT(*ref && (*ref)->fixed);
 
4080
        prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
 
4081
        prev_subselect_item->const_item_cache&= (*ref)->const_item();
 
4082
        break;
 
4083
      }
 
4084
    }
 
4085
 
 
4086
    /*
 
4087
      Reference is not found in this select => this subquery depend on
 
4088
      outer select (or we just trying to find wrong identifier, in this
 
4089
      case it does not matter which used tables bits we set)
 
4090
    */
 
4091
    prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
 
4092
    prev_subselect_item->const_item_cache= 0;
 
4093
  }
 
4094
 
 
4095
  DBUG_ASSERT(ref != 0);
 
4096
  if (!*from_field)
 
4097
    return -1;
 
4098
  if (ref == not_found_item && *from_field == not_found_field)
 
4099
  {
 
4100
    if (upward_lookup)
 
4101
    {
 
4102
      // We can't say exactly what absent table or field
 
4103
      my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where);
 
4104
    }
 
4105
    else
 
4106
    {
 
4107
      /* Call find_field_in_tables only to report the error */
 
4108
      find_field_in_tables(thd, this,
 
4109
                           context->first_name_resolution_table,
 
4110
                           context->last_name_resolution_table,
 
4111
                           reference, REPORT_ALL_ERRORS,
 
4112
                           !any_privileges &&
 
4113
                           TRUE, TRUE);
 
4114
    }
 
4115
    return -1;
 
4116
  }
 
4117
  else if (ref != not_found_item)
 
4118
  {
 
4119
    Item *save;
 
4120
    Item_ref *rf;
 
4121
 
 
4122
    /* Should have been checked in resolve_ref_in_select_and_group(). */
 
4123
    DBUG_ASSERT(*ref && (*ref)->fixed);
 
4124
    /*
 
4125
      Here, a subset of actions performed by Item_ref::set_properties
 
4126
      is not enough. So we pass ptr to NULL into Item_[direct]_ref
 
4127
      constructor, so no initialization is performed, and call 
 
4128
      fix_fields() below.
 
4129
    */
 
4130
    save= *ref;
 
4131
    *ref= NULL;                             // Don't call set_properties()
 
4132
    rf= (place == IN_HAVING ?
 
4133
         new Item_ref(context, ref, (char*) table_name,
 
4134
                      (char*) field_name, alias_name_used) :
 
4135
         (!select->group_list.elements ?
 
4136
         new Item_direct_ref(context, ref, (char*) table_name,
 
4137
                             (char*) field_name, alias_name_used) :
 
4138
         new Item_outer_ref(context, ref, (char*) table_name,
 
4139
                            (char*) field_name, alias_name_used)));
 
4140
    *ref= save;
 
4141
    if (!rf)
 
4142
      return -1;
 
4143
 
 
4144
    if (place != IN_HAVING && select->group_list.elements)
 
4145
    {
 
4146
      outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf);
 
4147
      ((Item_outer_ref*)rf)->in_sum_func= thd->lex->in_sum_func;
 
4148
    }
 
4149
    thd->change_item_tree(reference, rf);
 
4150
    /*
 
4151
      rf is Item_ref => never substitute other items (in this case)
 
4152
      during fix_fields() => we can use rf after fix_fields()
 
4153
    */
 
4154
    DBUG_ASSERT(!rf->fixed);                // Assured by Item_ref()
 
4155
    if (rf->fix_fields(thd, reference) || rf->check_cols(1))
 
4156
      return -1;
 
4157
 
 
4158
    mark_as_dependent(thd, last_checked_context->select_lex,
 
4159
                      context->select_lex, this,
 
4160
                      rf);
 
4161
    return 0;
 
4162
  }
 
4163
  else
 
4164
  {
 
4165
    mark_as_dependent(thd, last_checked_context->select_lex,
 
4166
                      context->select_lex,
 
4167
                      this, (Item_ident*)*reference);
 
4168
    if (last_checked_context->select_lex->having_fix_field)
 
4169
    {
 
4170
      Item_ref *rf;
 
4171
      rf= new Item_ref(context,
 
4172
                       (cached_table->db[0] ? cached_table->db : 0),
 
4173
                       (char*) cached_table->alias, (char*) field_name);
 
4174
      if (!rf)
 
4175
        return -1;
 
4176
      thd->change_item_tree(reference, rf);
 
4177
      /*
 
4178
        rf is Item_ref => never substitute other items (in this case)
 
4179
        during fix_fields() => we can use rf after fix_fields()
 
4180
      */
 
4181
      DBUG_ASSERT(!rf->fixed);                // Assured by Item_ref()
 
4182
      if (rf->fix_fields(thd, reference) || rf->check_cols(1))
 
4183
        return -1;
 
4184
      return 0;
 
4185
    }
 
4186
  }
 
4187
  return 1;
 
4188
}
 
4189
 
 
4190
 
 
4191
/**
 
4192
  Resolve the name of a column reference.
 
4193
 
 
4194
  The method resolves the column reference represented by 'this' as a column
 
4195
  present in one of: FROM clause, SELECT clause, GROUP BY clause of a query
 
4196
  Q, or in outer queries that contain Q.
 
4197
 
 
4198
  The name resolution algorithm used is (where [T_j] is an optional table
 
4199
  name that qualifies the column name):
 
4200
 
 
4201
  @code
 
4202
    resolve_column_reference([T_j].col_ref_i)
 
4203
    {
 
4204
      search for a column or derived column named col_ref_i
 
4205
      [in table T_j] in the FROM clause of Q;
 
4206
 
 
4207
      if such a column is NOT found AND    // Lookup in outer queries.
 
4208
         there are outer queries
 
4209
      {
 
4210
        for each outer query Q_k beginning from the inner-most one
 
4211
        {
 
4212
          search for a column or derived column named col_ref_i
 
4213
          [in table T_j] in the FROM clause of Q_k;
 
4214
 
 
4215
          if such a column is not found
 
4216
            Search for a column or derived column named col_ref_i
 
4217
            [in table T_j] in the SELECT and GROUP clauses of Q_k.
 
4218
        }
 
4219
      }
 
4220
    }
 
4221
  @endcode
 
4222
 
 
4223
    Notice that compared to Item_ref::fix_fields, here we first search the FROM
 
4224
    clause, and then we search the SELECT and GROUP BY clauses.
 
4225
 
 
4226
  @param[in]     thd        current thread
 
4227
  @param[in,out] reference  view column if this item was resolved to a
 
4228
    view column
 
4229
 
 
4230
  @retval
 
4231
    TRUE  if error
 
4232
  @retval
 
4233
    FALSE on success
 
4234
*/
 
4235
 
 
4236
bool Item_field::fix_fields(THD *thd, Item **reference)
 
4237
{
 
4238
  DBUG_ASSERT(fixed == 0);
 
4239
  Field *from_field= (Field *)not_found_field;
 
4240
  bool outer_fixed= false;
 
4241
 
 
4242
  if (!field)                                   // If field is not checked
 
4243
  {
 
4244
    /*
 
4245
      In case of view, find_field_in_tables() write pointer to view field
 
4246
      expression to 'reference', i.e. it substitute that expression instead
 
4247
      of this Item_field
 
4248
    */
 
4249
    if ((from_field= find_field_in_tables(thd, this,
 
4250
                                          context->first_name_resolution_table,
 
4251
                                          context->last_name_resolution_table,
 
4252
                                          reference,
 
4253
                                          thd->lex->use_only_table_context ?
 
4254
                                            REPORT_ALL_ERRORS : 
 
4255
                                            IGNORE_EXCEPT_NON_UNIQUE,
 
4256
                                          !any_privileges,
 
4257
                                          TRUE)) ==
 
4258
        not_found_field)
 
4259
    {
 
4260
      int ret;
 
4261
      /* Look up in current select's item_list to find aliased fields */
 
4262
      if (thd->lex->current_select->is_item_list_lookup)
 
4263
      {
 
4264
        uint counter;
 
4265
        enum_resolution_type resolution;
 
4266
        Item** res= find_item_in_list(this, thd->lex->current_select->item_list,
 
4267
                                      &counter, REPORT_EXCEPT_NOT_FOUND,
 
4268
                                      &resolution);
 
4269
        if (!res)
 
4270
          return 1;
 
4271
        if (resolution == RESOLVED_AGAINST_ALIAS)
 
4272
          alias_name_used= TRUE;
 
4273
        if (res != (Item **)not_found_item)
 
4274
        {
 
4275
          if ((*res)->type() == Item::FIELD_ITEM)
 
4276
          {
 
4277
            /*
 
4278
              It's an Item_field referencing another Item_field in the select
 
4279
              list.
 
4280
              Use the field from the Item_field in the select list and leave
 
4281
              the Item_field instance in place.
 
4282
            */
 
4283
 
 
4284
            Field *new_field= (*((Item_field**)res))->field;
 
4285
 
 
4286
            if (new_field == NULL)
 
4287
            {
 
4288
              /* The column to which we link isn't valid. */
 
4289
              my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->name, 
 
4290
                       current_thd->where);
 
4291
              return(1);
 
4292
            }
 
4293
 
 
4294
            set_field(new_field);
 
4295
            return 0;
 
4296
          }
 
4297
          else
 
4298
          {
 
4299
            /*
 
4300
              It's not an Item_field in the select list so we must make a new
 
4301
              Item_ref to point to the Item in the select list and replace the
 
4302
              Item_field created by the parser with the new Item_ref.
 
4303
 
 
4304
              NOTE: If we are fixing an alias reference inside ORDER/GROUP BY
 
4305
              item tree, then we use new Item_ref as an intermediate value
 
4306
              to resolve referenced item only.
 
4307
              In this case the new Item_ref item is unused.
 
4308
            */
 
4309
            Item_ref *rf= new Item_ref(context, db_name,table_name,field_name);
 
4310
            if (!rf)
 
4311
              return 1;
 
4312
 
 
4313
            bool save_group_fix_field= thd->lex->current_select->group_fix_field;
 
4314
            /*
 
4315
              No need for recursive resolving of aliases.
 
4316
            */
 
4317
            thd->lex->current_select->group_fix_field= 0;
 
4318
 
 
4319
            bool ret= rf->fix_fields(thd, (Item **) &rf) || rf->check_cols(1);
 
4320
            thd->lex->current_select->group_fix_field= save_group_fix_field;
 
4321
            if (ret)
 
4322
              return TRUE;
 
4323
 
 
4324
            if (save_group_fix_field && alias_name_used)
 
4325
              thd->change_item_tree(reference, *rf->ref);
 
4326
            else
 
4327
              thd->change_item_tree(reference, rf);
 
4328
 
 
4329
            return FALSE;
 
4330
          }
 
4331
        }
 
4332
      }
 
4333
      if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
 
4334
        goto error;
 
4335
      outer_fixed= TRUE;
 
4336
      if (!ret)
 
4337
        goto mark_non_agg_field;
 
4338
    }
 
4339
    else if (!from_field)
 
4340
      goto error;
 
4341
 
 
4342
    if (!outer_fixed && cached_table && cached_table->select_lex &&
 
4343
        context->select_lex &&
 
4344
        cached_table->select_lex != context->select_lex)
 
4345
    {
 
4346
      int ret;
 
4347
      if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
 
4348
        goto error;
 
4349
      outer_fixed= 1;
 
4350
      if (!ret)
 
4351
        goto mark_non_agg_field;
 
4352
    }
 
4353
 
 
4354
    /*
 
4355
      if it is not expression from merged VIEW we will set this field.
 
4356
 
 
4357
      We can leave expression substituted from view for next PS/SP rexecution
 
4358
      (i.e. do not register this substitution for reverting on cleanup()
 
4359
      (register_item_tree_changing())), because this subtree will be
 
4360
      fix_field'ed during setup_tables()->setup_underlying() (i.e. before
 
4361
      all other expressions of query, and references on tables which do
 
4362
      not present in query will not make problems.
 
4363
 
 
4364
      Also we suppose that view can't be changed during PS/SP life.
 
4365
    */
 
4366
    if (from_field == view_ref_found)
 
4367
      return FALSE;
 
4368
 
 
4369
    set_field(from_field);
 
4370
    if (thd->lex->in_sum_func &&
 
4371
        thd->lex->in_sum_func->nest_level == 
 
4372
        thd->lex->current_select->nest_level)
 
4373
      set_if_bigger(thd->lex->in_sum_func->max_arg_level,
 
4374
                    thd->lex->current_select->nest_level);
 
4375
  }
 
4376
  else if (thd->mark_used_columns != MARK_COLUMNS_NONE)
 
4377
  {
 
4378
    TABLE *table= field->table;
 
4379
    MY_BITMAP *current_bitmap, *other_bitmap;
 
4380
    if (thd->mark_used_columns == MARK_COLUMNS_READ)
 
4381
    {
 
4382
      current_bitmap= table->read_set;
 
4383
      other_bitmap=   table->write_set;
 
4384
    }
 
4385
    else
 
4386
    {
 
4387
      current_bitmap= table->write_set;
 
4388
      other_bitmap=   table->read_set;
 
4389
    }
 
4390
    if (!bitmap_fast_test_and_set(current_bitmap, field->field_index))
 
4391
    {
 
4392
      if (!bitmap_is_set(other_bitmap, field->field_index))
 
4393
      {
 
4394
        /* First usage of column */
 
4395
        table->used_fields++;                     // Used to optimize loops
 
4396
        /* purecov: begin inspected */
 
4397
        table->covering_keys.intersect(field->part_of_key);
 
4398
        /* purecov: end */
 
4399
      }
 
4400
    }
 
4401
  }
 
4402
#ifndef NO_EMBEDDED_ACCESS_CHECKS
 
4403
  if (any_privileges)
 
4404
  {
 
4405
    char *db, *tab;
 
4406
    db= cached_table->get_db_name();
 
4407
    tab= cached_table->get_table_name();
 
4408
    if (!(have_privileges= (get_column_grant(thd, &field->table->grant,
 
4409
                                             db, tab, field_name) &
 
4410
                            VIEW_ANY_ACL)))
 
4411
    {
 
4412
      my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
 
4413
               "ANY", thd->security_ctx->priv_user,
 
4414
               thd->security_ctx->host_or_ip, field_name, tab);
 
4415
      goto error;
 
4416
    }
 
4417
  }
 
4418
#endif
 
4419
  fixed= 1;
 
4420
  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
 
4421
      !outer_fixed && !thd->lex->in_sum_func &&
 
4422
      thd->lex->current_select->cur_pos_in_select_list != UNDEF_POS)
 
4423
  {
 
4424
    thd->lex->current_select->non_agg_fields.push_back(this);
 
4425
    marker= thd->lex->current_select->cur_pos_in_select_list;
 
4426
  }
 
4427
mark_non_agg_field:
 
4428
  if (fixed && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
 
4429
  {
 
4430
    /*
 
4431
      Mark selects according to presence of non aggregated fields.
 
4432
      Fields from outer selects added to the aggregate function
 
4433
      outer_fields list as its unknown at the moment whether it's
 
4434
      aggregated or not.
 
4435
      We're using either the select lex of the cached table (if present)
 
4436
      or the field's resolution context. context->select_lex is 
 
4437
      safe for use because it's either the SELECT we want to use 
 
4438
      (the current level) or a stub added by non-SELECT queries.
 
4439
    */
 
4440
    SELECT_LEX *select_lex= cached_table ? 
 
4441
      cached_table->select_lex : context->select_lex;
 
4442
    if (!thd->lex->in_sum_func)
 
4443
      select_lex->full_group_by_flag|= NON_AGG_FIELD_USED;
 
4444
    else
 
4445
    {
 
4446
      if (outer_fixed)
 
4447
        thd->lex->in_sum_func->outer_fields.push_back(this);
 
4448
      else if (thd->lex->in_sum_func->nest_level !=
 
4449
          thd->lex->current_select->nest_level)
 
4450
        select_lex->full_group_by_flag|= NON_AGG_FIELD_USED;
 
4451
    }
 
4452
  }
 
4453
  return FALSE;
 
4454
 
 
4455
error:
 
4456
  context->process_error(thd);
 
4457
  return TRUE;
 
4458
}
 
4459
 
 
4460
 
 
4461
Item *Item_field::safe_charset_converter(CHARSET_INFO *tocs)
 
4462
{
 
4463
  no_const_subst= 1;
 
4464
  return Item::safe_charset_converter(tocs);
 
4465
}
 
4466
 
 
4467
 
 
4468
void Item_field::cleanup()
 
4469
{
 
4470
  DBUG_ENTER("Item_field::cleanup");
 
4471
  Item_ident::cleanup();
 
4472
  /*
 
4473
    Even if this object was created by direct link to field in setup_wild()
 
4474
    it will be linked correctly next time by name of field and table alias.
 
4475
    I.e. we can drop 'field'.
 
4476
   */
 
4477
  field= result_field= 0;
 
4478
  null_value= FALSE;
 
4479
  DBUG_VOID_RETURN;
 
4480
}
 
4481
 
 
4482
/**
 
4483
  Find a field among specified multiple equalities.
 
4484
 
 
4485
  The function first searches the field among multiple equalities
 
4486
  of the current level (in the cond_equal->current_level list).
 
4487
  If it fails, it continues searching in upper levels accessed
 
4488
  through a pointer cond_equal->upper_levels.
 
4489
  The search terminates as soon as a multiple equality containing 
 
4490
  the field is found. 
 
4491
 
 
4492
  @param cond_equal   reference to list of multiple equalities where
 
4493
                      the field (this object) is to be looked for
 
4494
 
 
4495
  @return
 
4496
    - First Item_equal containing the field, if success
 
4497
    - 0, otherwise
 
4498
*/
 
4499
 
 
4500
Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal)
 
4501
{
 
4502
  Item_equal *item= 0;
 
4503
  while (cond_equal)
 
4504
  {
 
4505
    List_iterator_fast<Item_equal> li(cond_equal->current_level);
 
4506
    while ((item= li++))
 
4507
    {
 
4508
      if (item->contains(field))
 
4509
        return item;
 
4510
    }
 
4511
    /* 
 
4512
      The field is not found in any of the multiple equalities
 
4513
      of the current level. Look for it in upper levels
 
4514
    */
 
4515
    cond_equal= cond_equal->upper_levels;
 
4516
  }
 
4517
  return 0;
 
4518
}
 
4519
 
 
4520
 
 
4521
/**
 
4522
  Check whether a field can be substituted by an equal item.
 
4523
 
 
4524
  The function checks whether a substitution of the field
 
4525
  occurrence for an equal item is valid.
 
4526
 
 
4527
  @param arg   *arg != NULL <-> the field is in the context where
 
4528
               substitution for an equal item is valid
 
4529
 
 
4530
  @note
 
4531
    The following statement is not always true:
 
4532
  @n
 
4533
    x=y => F(x)=F(x/y).
 
4534
  @n
 
4535
    This means substitution of an item for an equal item not always
 
4536
    yields an equavalent condition. Here's an example:
 
4537
    @code
 
4538
    'a'='a '
 
4539
    (LENGTH('a')=1) != (LENGTH('a ')=2)
 
4540
  @endcode
 
4541
    Such a substitution is surely valid if either the substituted
 
4542
    field is not of a STRING type or if it is an argument of
 
4543
    a comparison predicate.
 
4544
 
 
4545
  @retval
 
4546
    TRUE   substitution is valid
 
4547
  @retval
 
4548
    FALSE  otherwise
 
4549
*/
 
4550
 
 
4551
bool Item_field::subst_argument_checker(uchar **arg)
 
4552
{
 
4553
  return (result_type() != STRING_RESULT) || (*arg);
 
4554
}
 
4555
 
 
4556
 
 
4557
/**
 
4558
  Convert a numeric value to a zero-filled string
 
4559
 
 
4560
  @param[in,out]  item   the item to operate on
 
4561
  @param          field  The field that this value is equated to
 
4562
 
 
4563
  This function converts a numeric value to a string. In this conversion
 
4564
  the zero-fill flag of the field is taken into account.
 
4565
  This is required so the resulting string value can be used instead of
 
4566
  the field reference when propagating equalities.
 
4567
*/
 
4568
 
 
4569
static void convert_zerofill_number_to_string(Item **item, Field_num *field)
 
4570
{
 
4571
  char buff[MAX_FIELD_WIDTH],*pos;
 
4572
  String tmp(buff,sizeof(buff), field->charset()), *res;
 
4573
 
 
4574
  res= (*item)->val_str(&tmp);
 
4575
  if ((*item)->is_null())
 
4576
    *item= new Item_null();
 
4577
  else
 
4578
  {
 
4579
    field->prepend_zeros(res);
 
4580
    pos= (char *) sql_strmake (res->ptr(), res->length());
 
4581
    *item= new Item_string(pos, res->length(), field->charset());
 
4582
  }
 
4583
}
 
4584
 
 
4585
 
 
4586
/**
 
4587
  Set a pointer to the multiple equality the field reference belongs to
 
4588
  (if any).
 
4589
 
 
4590
  The function looks for a multiple equality containing the field item
 
4591
  among those referenced by arg.
 
4592
  In the case such equality exists the function does the following.
 
4593
  If the found multiple equality contains a constant, then the field
 
4594
  reference is substituted for this constant, otherwise it sets a pointer
 
4595
  to the multiple equality in the field item.
 
4596
 
 
4597
 
 
4598
  @param arg    reference to list of multiple equalities where
 
4599
                the field (this object) is to be looked for
 
4600
 
 
4601
  @note
 
4602
    This function is supposed to be called as a callback parameter in calls
 
4603
    of the compile method.
 
4604
 
 
4605
  @return
 
4606
    - pointer to the replacing constant item, if the field item was substituted
 
4607
    - pointer to the field item, otherwise.
 
4608
*/
 
4609
 
 
4610
Item *Item_field::equal_fields_propagator(uchar *arg)
 
4611
{
 
4612
  if (no_const_subst)
 
4613
    return this;
 
4614
  item_equal= find_item_equal((COND_EQUAL *) arg);
 
4615
  Item *item= 0;
 
4616
  if (item_equal)
 
4617
    item= item_equal->get_const();
 
4618
  /*
 
4619
    Disable const propagation for items used in different comparison contexts.
 
4620
    This must be done because, for example, Item_hex_string->val_int() is not
 
4621
    the same as (Item_hex_string->val_str() in BINARY column)->val_int().
 
4622
    We cannot simply disable the replacement in a particular context (
 
4623
    e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
 
4624
    Items don't know the context they are in and there are functions like 
 
4625
    IF (<hex_string>, 'yes', 'no').
 
4626
    The same problem occurs when comparing a DATE/TIME field with a
 
4627
    DATE/TIME represented as an int and as a string.
 
4628
  */
 
4629
  if (!item ||
 
4630
      (cmp_context != (Item_result)-1 && item->cmp_context != cmp_context))
 
4631
    item= this;
 
4632
  else if (field && (field->flags & ZEROFILL_FLAG) && IS_NUM(field->type()))
 
4633
  {
 
4634
    /*
 
4635
      We don't need to zero-fill timestamp columns here because they will be 
 
4636
      first converted to a string (in date/time format) and compared as such if
 
4637
      compared with another string.
 
4638
    */
 
4639
    if (item && field->type() != FIELD_TYPE_TIMESTAMP && cmp_context != INT_RESULT)
 
4640
      convert_zerofill_number_to_string(&item, (Field_num *)field);
 
4641
    else
 
4642
      item= this;
 
4643
  }
 
4644
  return item;
 
4645
}
 
4646
 
 
4647
 
 
4648
/**
 
4649
  Mark the item to not be part of substitution if it's not a binary item.
 
4650
 
 
4651
  See comments in Arg_comparator::set_compare_func() for details.
 
4652
*/
 
4653
 
 
4654
bool Item_field::set_no_const_sub(uchar *arg)
 
4655
{
 
4656
  if (field->charset() != &my_charset_bin)
 
4657
    no_const_subst=1;
 
4658
  return FALSE;
 
4659
}
 
4660
 
 
4661
 
 
4662
/**
 
4663
  Replace an Item_field for an equal Item_field that evaluated earlier
 
4664
  (if any).
 
4665
 
 
4666
  The function returns a pointer to an item that is taken from
 
4667
  the very beginning of the item_equal list which the Item_field
 
4668
  object refers to (belongs to) unless item_equal contains  a constant
 
4669
  item. In this case the function returns this constant item, 
 
4670
  (if the substitution does not require conversion).   
 
4671
  If the Item_field object does not refer any Item_equal object
 
4672
  'this' is returned .
 
4673
 
 
4674
  @param arg   a dummy parameter, is not used here
 
4675
 
 
4676
 
 
4677
  @note
 
4678
    This function is supposed to be called as a callback parameter in calls
 
4679
    of the thransformer method.
 
4680
 
 
4681
  @return
 
4682
    - pointer to a replacement Item_field if there is a better equal item or
 
4683
      a pointer to a constant equal item;
 
4684
    - this - otherwise.
 
4685
*/
 
4686
 
 
4687
Item *Item_field::replace_equal_field(uchar *arg)
 
4688
{
 
4689
  if (item_equal)
 
4690
  {
 
4691
    Item *const_item= item_equal->get_const();
 
4692
    if (const_item)
 
4693
    {
 
4694
      if (cmp_context != (Item_result)-1 &&
 
4695
          const_item->cmp_context != cmp_context)
 
4696
        return this;
 
4697
      return const_item;
 
4698
    }
 
4699
    Item_field *subst= item_equal->get_first();
 
4700
    if (subst && field->table != subst->field->table && !field->eq(subst->field))
 
4701
      return subst;
 
4702
  }
 
4703
  return this;
 
4704
}
 
4705
 
 
4706
 
 
4707
void Item::init_make_field(Send_field *tmp_field,
 
4708
                           enum enum_field_types field_type_arg)
 
4709
{
 
4710
  char *empty_name= (char*) "";
 
4711
  tmp_field->db_name=           empty_name;
 
4712
  tmp_field->org_table_name=    empty_name;
 
4713
  tmp_field->org_col_name=      empty_name;
 
4714
  tmp_field->table_name=        empty_name;
 
4715
  tmp_field->col_name=          name;
 
4716
  tmp_field->charsetnr=         collation.collation->number;
 
4717
  tmp_field->flags=             (maybe_null ? 0 : NOT_NULL_FLAG) | 
 
4718
                                (my_binary_compare(collation.collation) ?
 
4719
                                 BINARY_FLAG : 0);
 
4720
  tmp_field->type=              field_type_arg;
 
4721
  tmp_field->length=max_length;
 
4722
  tmp_field->decimals=decimals;
 
4723
  if (unsigned_flag)
 
4724
    tmp_field->flags |= UNSIGNED_FLAG;
 
4725
}
 
4726
 
 
4727
void Item::make_field(Send_field *tmp_field)
 
4728
{
 
4729
  init_make_field(tmp_field, field_type());
 
4730
}
 
4731
 
 
4732
 
 
4733
enum_field_types Item::string_field_type() const
 
4734
{
 
4735
  enum_field_types f_type= MYSQL_TYPE_VAR_STRING;
 
4736
  if (max_length >= 16777216)
 
4737
    f_type= MYSQL_TYPE_LONG_BLOB;
 
4738
  else if (max_length >= 65536)
 
4739
    f_type= MYSQL_TYPE_MEDIUM_BLOB;
 
4740
  return f_type;
 
4741
}
 
4742
 
 
4743
 
 
4744
void Item_empty_string::make_field(Send_field *tmp_field)
 
4745
{
 
4746
  init_make_field(tmp_field, string_field_type());
 
4747
}
 
4748
 
 
4749
 
 
4750
enum_field_types Item::field_type() const
 
4751
{
 
4752
  switch (result_type()) {
 
4753
  case STRING_RESULT:  return string_field_type();
 
4754
  case INT_RESULT:     return MYSQL_TYPE_LONGLONG;
 
4755
  case DECIMAL_RESULT: return MYSQL_TYPE_NEWDECIMAL;
 
4756
  case REAL_RESULT:    return MYSQL_TYPE_DOUBLE;
 
4757
  case ROW_RESULT:
 
4758
  default:
 
4759
    DBUG_ASSERT(0);
 
4760
    return MYSQL_TYPE_VARCHAR;
 
4761
  }
 
4762
}
 
4763
 
 
4764
 
 
4765
bool Item::is_datetime()
 
4766
{
 
4767
  switch (field_type())
 
4768
  {
 
4769
    case MYSQL_TYPE_DATE:
 
4770
    case MYSQL_TYPE_DATETIME:
 
4771
    case MYSQL_TYPE_TIMESTAMP:
 
4772
      return TRUE;
 
4773
    default:
 
4774
      break;
 
4775
  }
 
4776
  return FALSE;
 
4777
}
 
4778
 
 
4779
 
 
4780
String *Item::check_well_formed_result(String *str, bool send_error)
 
4781
{
 
4782
  /* Check whether we got a well-formed string */
 
4783
  CHARSET_INFO *cs= str->charset();
 
4784
  int well_formed_error;
 
4785
  uint wlen= cs->cset->well_formed_len(cs,
 
4786
                                       str->ptr(), str->ptr() + str->length(),
 
4787
                                       str->length(), &well_formed_error);
 
4788
  if (wlen < str->length())
 
4789
  {
 
4790
    THD *thd= current_thd;
 
4791
    char hexbuf[7];
 
4792
    enum MYSQL_ERROR::enum_warning_level level;
 
4793
    uint diff= str->length() - wlen;
 
4794
    set_if_smaller(diff, 3);
 
4795
    octet2hex(hexbuf, str->ptr() + wlen, diff);
 
4796
    if (send_error)
 
4797
    {
 
4798
      my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
 
4799
               cs->csname,  hexbuf);
 
4800
      return 0;
 
4801
    }
 
4802
    if ((thd->variables.sql_mode &
 
4803
         (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)))
 
4804
    {
 
4805
      level= MYSQL_ERROR::WARN_LEVEL_ERROR;
 
4806
      null_value= 1;
 
4807
      str= 0;
 
4808
    }
 
4809
    else
 
4810
    {
 
4811
      level= MYSQL_ERROR::WARN_LEVEL_WARN;
 
4812
      str->length(wlen);
 
4813
    }
 
4814
    push_warning_printf(thd, level, ER_INVALID_CHARACTER_STRING,
 
4815
                        ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
 
4816
  }
 
4817
  return str;
 
4818
}
 
4819
 
 
4820
/*
 
4821
  Compare two items using a given collation
 
4822
  
 
4823
  SYNOPSIS
 
4824
    eq_by_collation()
 
4825
    item               item to compare with
 
4826
    binary_cmp         TRUE <-> compare as binaries
 
4827
    cs                 collation to use when comparing strings
 
4828
 
 
4829
  DESCRIPTION
 
4830
    This method works exactly as Item::eq if the collation cs coincides with
 
4831
    the collation of the compared objects. Otherwise, first the collations that
 
4832
    differ from cs are replaced for cs and then the items are compared by
 
4833
    Item::eq. After the comparison the original collations of items are
 
4834
    restored.
 
4835
 
 
4836
  RETURN
 
4837
    1    compared items has been detected as equal   
 
4838
    0    otherwise
 
4839
*/
 
4840
 
 
4841
bool Item::eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs)
 
4842
{
 
4843
  CHARSET_INFO *save_cs= 0;
 
4844
  CHARSET_INFO *save_item_cs= 0;
 
4845
  if (collation.collation != cs)
 
4846
  {
 
4847
    save_cs= collation.collation;
 
4848
    collation.collation= cs;
 
4849
  }
 
4850
  if (item->collation.collation != cs)
 
4851
  {
 
4852
    save_item_cs= item->collation.collation;
 
4853
    item->collation.collation= cs;
 
4854
  }
 
4855
  bool res= eq(item, binary_cmp);
 
4856
  if (save_cs)
 
4857
    collation.collation= save_cs;
 
4858
  if (save_item_cs)
 
4859
    item->collation.collation= save_item_cs;
 
4860
  return res;
 
4861
}  
 
4862
 
 
4863
 
 
4864
/**
 
4865
  Create a field to hold a string value from an item.
 
4866
 
 
4867
  If max_length > CONVERT_IF_BIGGER_TO_BLOB create a blob @n
 
4868
  If max_length > 0 create a varchar @n
 
4869
  If max_length == 0 create a CHAR(0) 
 
4870
 
 
4871
  @param table          Table for which the field is created
 
4872
*/
 
4873
 
 
4874
Field *Item::make_string_field(TABLE *table)
 
4875
{
 
4876
  Field *field;
 
4877
  DBUG_ASSERT(collation.collation);
 
4878
  if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB)
 
4879
    field= new Field_blob(max_length, maybe_null, name,
 
4880
                          collation.collation);
 
4881
  /* Item_type_holder holds the exact type, do not change it */
 
4882
  else if (max_length > 0 &&
 
4883
      (type() != Item::TYPE_HOLDER || field_type() != MYSQL_TYPE_STRING))
 
4884
    field= new Field_varstring(max_length, maybe_null, name, table->s,
 
4885
                               collation.collation);
 
4886
  else
 
4887
    field= new Field_string(max_length, maybe_null, name,
 
4888
                            collation.collation);
 
4889
  if (field)
 
4890
    field->init(table);
 
4891
  return field;
 
4892
}
 
4893
 
 
4894
 
 
4895
/**
 
4896
  Create a field based on field_type of argument.
 
4897
 
 
4898
  For now, this is only used to create a field for
 
4899
  IFNULL(x,something) and time functions
 
4900
 
 
4901
  @retval
 
4902
    NULL  error
 
4903
  @retval
 
4904
    \#    Created field
 
4905
*/
 
4906
 
 
4907
Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length)
 
4908
{
 
4909
  /*
 
4910
    The field functions defines a field to be not null if null_ptr is not 0
 
4911
  */
 
4912
  uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
 
4913
  Field *field;
 
4914
 
 
4915
  switch (field_type()) {
 
4916
  case MYSQL_TYPE_DECIMAL:
 
4917
  case MYSQL_TYPE_NEWDECIMAL:
 
4918
    field= Field_new_decimal::create_from_item(this);
 
4919
    break;
 
4920
  case MYSQL_TYPE_TINY:
 
4921
    field= new Field_tiny((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4922
                          name, 0, unsigned_flag);
 
4923
    break;
 
4924
  case MYSQL_TYPE_SHORT:
 
4925
    field= new Field_short((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4926
                           name, 0, unsigned_flag);
 
4927
    break;
 
4928
  case MYSQL_TYPE_LONG:
 
4929
    field= new Field_long((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4930
                          name, 0, unsigned_flag);
 
4931
    break;
 
4932
#ifdef HAVE_LONG_LONG
 
4933
  case MYSQL_TYPE_LONGLONG:
 
4934
    field= new Field_longlong((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4935
                              name, 0, unsigned_flag);
 
4936
    break;
 
4937
#endif
 
4938
  case MYSQL_TYPE_FLOAT:
 
4939
    field= new Field_float((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4940
                           name, decimals, 0, unsigned_flag);
 
4941
    break;
 
4942
  case MYSQL_TYPE_DOUBLE:
 
4943
    field= new Field_double((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4944
                            name, decimals, 0, unsigned_flag);
 
4945
    break;
 
4946
  case MYSQL_TYPE_NULL:
 
4947
    field= new Field_null((uchar*) 0, max_length, Field::NONE,
 
4948
                          name, &my_charset_bin);
 
4949
    break;
 
4950
  case MYSQL_TYPE_INT24:
 
4951
    field= new Field_medium((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4952
                            name, 0, unsigned_flag);
 
4953
    break;
 
4954
  case MYSQL_TYPE_NEWDATE:
 
4955
  case MYSQL_TYPE_DATE:
 
4956
    field= new Field_newdate(maybe_null, name, &my_charset_bin);
 
4957
    break;
 
4958
  case MYSQL_TYPE_TIME:
 
4959
    field= new Field_time(maybe_null, name, &my_charset_bin);
 
4960
    break;
 
4961
  case MYSQL_TYPE_TIMESTAMP:
 
4962
    field= new Field_timestamp(maybe_null, name, &my_charset_bin);
 
4963
    break;
 
4964
  case MYSQL_TYPE_DATETIME:
 
4965
    field= new Field_datetime(maybe_null, name, &my_charset_bin);
 
4966
    break;
 
4967
  case MYSQL_TYPE_YEAR:
 
4968
    field= new Field_year((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 
4969
                          name);
 
4970
    break;
 
4971
  case MYSQL_TYPE_BIT:
 
4972
    field= new Field_bit_as_char(NULL, max_length, null_ptr, 0,
 
4973
                                 Field::NONE, name);
 
4974
    break;
 
4975
  default:
 
4976
    /* This case should never be chosen */
 
4977
    DBUG_ASSERT(0);
 
4978
    /* If something goes awfully wrong, it's better to get a string than die */
 
4979
  case MYSQL_TYPE_STRING:
 
4980
    if (fixed_length && max_length < CONVERT_IF_BIGGER_TO_BLOB)
 
4981
    {
 
4982
      field= new Field_string(max_length, maybe_null, name,
 
4983
                              collation.collation);
 
4984
      break;
 
4985
    }
 
4986
    /* Fall through to make_string_field() */
 
4987
  case MYSQL_TYPE_ENUM:
 
4988
  case MYSQL_TYPE_SET:
 
4989
  case MYSQL_TYPE_VAR_STRING:
 
4990
  case MYSQL_TYPE_VARCHAR:
 
4991
    return make_string_field(table);
 
4992
  case MYSQL_TYPE_TINY_BLOB:
 
4993
  case MYSQL_TYPE_MEDIUM_BLOB:
 
4994
  case MYSQL_TYPE_LONG_BLOB:
 
4995
  case MYSQL_TYPE_BLOB:
 
4996
    if (this->type() == Item::TYPE_HOLDER)
 
4997
      field= new Field_blob(max_length, maybe_null, name, collation.collation,
 
4998
                            1);
 
4999
    else
 
5000
      field= new Field_blob(max_length, maybe_null, name, collation.collation);
 
5001
    break;                                      // Blob handled outside of case
 
5002
#ifdef HAVE_SPATIAL
 
5003
  case MYSQL_TYPE_GEOMETRY:
 
5004
    field= new Field_geom(max_length, maybe_null,
 
5005
                          name, table->s, get_geometry_type());
 
5006
#endif /* HAVE_SPATIAL */
 
5007
  }
 
5008
  if (field)
 
5009
    field->init(table);
 
5010
  return field;
 
5011
}
 
5012
 
 
5013
 
 
5014
/* ARGSUSED */
 
5015
void Item_field::make_field(Send_field *tmp_field)
 
5016
{
 
5017
  field->make_field(tmp_field);
 
5018
  DBUG_ASSERT(tmp_field->table_name != 0);
 
5019
  if (name)
 
5020
    tmp_field->col_name=name;                   // Use user supplied name
 
5021
  if (table_name)
 
5022
    tmp_field->table_name= table_name;
 
5023
  if (db_name)
 
5024
    tmp_field->db_name= db_name;
 
5025
}
 
5026
 
 
5027
 
 
5028
/**
 
5029
  Set a field's value from a item.
 
5030
*/
 
5031
 
 
5032
void Item_field::save_org_in_field(Field *to)
 
5033
{
 
5034
  if (field->is_null())
 
5035
  {
 
5036
    null_value=1;
 
5037
    set_field_to_null_with_conversions(to, 1);
 
5038
  }
 
5039
  else
 
5040
  {
 
5041
    to->set_notnull();
 
5042
    field_conv(to,field);
 
5043
    null_value=0;
 
5044
  }
 
5045
}
 
5046
 
 
5047
int Item_field::save_in_field(Field *to, bool no_conversions)
 
5048
{
 
5049
  int res;
 
5050
  if (result_field->is_null())
 
5051
  {
 
5052
    null_value=1;
 
5053
    res= set_field_to_null_with_conversions(to, no_conversions);
 
5054
  }
 
5055
  else
 
5056
  {
 
5057
    to->set_notnull();
 
5058
    res= field_conv(to,result_field);
 
5059
    null_value=0;
 
5060
  }
 
5061
  return res;
 
5062
}
 
5063
 
 
5064
 
 
5065
/**
 
5066
  Store null in field.
 
5067
 
 
5068
  This is used on INSERT.
 
5069
  Allow NULL to be inserted in timestamp and auto_increment values.
 
5070
 
 
5071
  @param field          Field where we want to store NULL
 
5072
 
 
5073
  @retval
 
5074
    0   ok
 
5075
  @retval
 
5076
    1   Field doesn't support NULL values and can't handle 'field = NULL'
 
5077
*/
 
5078
 
 
5079
int Item_null::save_in_field(Field *field, bool no_conversions)
 
5080
{
 
5081
  return set_field_to_null_with_conversions(field, no_conversions);
 
5082
}
 
5083
 
 
5084
 
 
5085
/**
 
5086
  Store null in field.
 
5087
 
 
5088
  @param field          Field where we want to store NULL
 
5089
 
 
5090
  @retval
 
5091
    0    OK
 
5092
  @retval
 
5093
    1    Field doesn't support NULL values
 
5094
*/
 
5095
 
 
5096
int Item_null::save_safe_in_field(Field *field)
 
5097
{
 
5098
  return set_field_to_null(field);
 
5099
}
 
5100
 
 
5101
 
 
5102
/*
 
5103
  This implementation can lose str_value content, so if the
 
5104
  Item uses str_value to store something, it should
 
5105
  reimplement it's ::save_in_field() as Item_string, for example, does.
 
5106
 
 
5107
  Note: all Item_XXX::val_str(str) methods must NOT rely on the fact that
 
5108
  str != str_value. For example, see fix for bug #44743.
 
5109
*/
 
5110
 
 
5111
int Item::save_in_field(Field *field, bool no_conversions)
 
5112
{
 
5113
  int error;
 
5114
  if (result_type() == STRING_RESULT ||
 
5115
      (result_type() == REAL_RESULT &&
 
5116
       field->result_type() == STRING_RESULT))
 
5117
  {
 
5118
    String *result;
 
5119
    CHARSET_INFO *cs= collation.collation;
 
5120
    char buff[MAX_FIELD_WIDTH];         // Alloc buffer for small columns
 
5121
    str_value.set_quick(buff, sizeof(buff), cs);
 
5122
    result=val_str(&str_value);
 
5123
    if (null_value)
 
5124
    {
 
5125
      str_value.set_quick(0, 0, cs);
 
5126
      return set_field_to_null_with_conversions(field, no_conversions);
 
5127
    }
 
5128
 
 
5129
    /* NOTE: If null_value == FALSE, "result" must be not NULL.  */
 
5130
 
 
5131
    field->set_notnull();
 
5132
    error=field->store(result->ptr(),result->length(),cs);
 
5133
    str_value.set_quick(0, 0, cs);
 
5134
  }
 
5135
  else if (result_type() == REAL_RESULT)
 
5136
  {
 
5137
    double nr= val_real();
 
5138
    if (null_value)
 
5139
      return set_field_to_null(field);
 
5140
    field->set_notnull();
 
5141
    error=field->store(nr);
 
5142
  }
 
5143
  else if (result_type() == DECIMAL_RESULT)
 
5144
  {
 
5145
    my_decimal decimal_value;
 
5146
    my_decimal *value= val_decimal(&decimal_value);
 
5147
    if (null_value)
 
5148
      return set_field_to_null_with_conversions(field, no_conversions);
 
5149
    field->set_notnull();
 
5150
    error=field->store_decimal(value);
 
5151
  }
 
5152
  else
 
5153
  {
 
5154
    longlong nr=val_int();
 
5155
    if (null_value)
 
5156
      return set_field_to_null_with_conversions(field, no_conversions);
 
5157
    field->set_notnull();
 
5158
    error=field->store(nr, unsigned_flag);
 
5159
  }
 
5160
  return error ? error : (field->table->in_use->is_error() ? 1 : 0);
 
5161
}
 
5162
 
 
5163
 
 
5164
int Item_string::save_in_field(Field *field, bool no_conversions)
 
5165
{
 
5166
  String *result;
 
5167
  result=val_str(&str_value);
 
5168
  return save_str_value_in_field(field, result);
 
5169
}
 
5170
 
 
5171
 
 
5172
int Item_uint::save_in_field(Field *field, bool no_conversions)
 
5173
{
 
5174
  /* Item_int::save_in_field handles both signed and unsigned. */
 
5175
  return Item_int::save_in_field(field, no_conversions);
 
5176
}
 
5177
 
 
5178
static int save_int_value_in_field (Field *field, longlong nr, 
 
5179
                                    bool null_value, bool unsigned_flag)
 
5180
{
 
5181
  if (null_value)
 
5182
    return set_field_to_null(field);
 
5183
  field->set_notnull();
 
5184
  return field->store(nr, unsigned_flag);
 
5185
}
 
5186
 
 
5187
 
 
5188
int Item_int::save_in_field(Field *field, bool no_conversions)
 
5189
{
 
5190
  return save_int_value_in_field (field, val_int(), null_value, unsigned_flag);
 
5191
}
 
5192
 
 
5193
 
 
5194
int Item_decimal::save_in_field(Field *field, bool no_conversions)
 
5195
{
 
5196
  field->set_notnull();
 
5197
  return field->store_decimal(&decimal_value);
 
5198
}
 
5199
 
 
5200
 
 
5201
bool Item_int::eq(const Item *arg, bool binary_cmp) const
 
5202
{
 
5203
  /* No need to check for null value as basic constant can't be NULL */
 
5204
  if (arg->basic_const_item() && arg->type() == type())
 
5205
  {
 
5206
    /*
 
5207
      We need to cast off const to call val_int(). This should be OK for
 
5208
      a basic constant.
 
5209
    */
 
5210
    Item *item= (Item*) arg;
 
5211
    return item->val_int() == value && item->unsigned_flag == unsigned_flag;
 
5212
  }
 
5213
  return FALSE;
 
5214
}
 
5215
 
 
5216
 
 
5217
Item *Item_int_with_ref::clone_item()
 
5218
{
 
5219
  DBUG_ASSERT(ref->const_item());
 
5220
  /*
 
5221
    We need to evaluate the constant to make sure it works with
 
5222
    parameter markers.
 
5223
  */
 
5224
  return (ref->unsigned_flag ?
 
5225
          new Item_uint(ref->name, ref->val_int(), ref->max_length) :
 
5226
          new Item_int(ref->name, ref->val_int(), ref->max_length));
 
5227
}
 
5228
 
 
5229
 
 
5230
Item_num *Item_uint::neg()
 
5231
{
 
5232
  Item_decimal *item= new Item_decimal(value, 1);
 
5233
  return item->neg();
 
5234
}
 
5235
 
 
5236
 
 
5237
static uint nr_of_decimals(const char *str, const char *end)
 
5238
{
 
5239
  const char *decimal_point;
 
5240
 
 
5241
  /* Find position for '.' */
 
5242
  for (;;)
 
5243
  {
 
5244
    if (str == end)
 
5245
      return 0;
 
5246
    if (*str == 'e' || *str == 'E')
 
5247
      return NOT_FIXED_DEC;    
 
5248
    if (*str++ == '.')
 
5249
      break;
 
5250
  }
 
5251
  decimal_point= str;
 
5252
  for (; my_isdigit(system_charset_info, *str) ; str++)
 
5253
    ;
 
5254
  if (*str == 'e' || *str == 'E')
 
5255
    return NOT_FIXED_DEC;
 
5256
  return (uint) (str - decimal_point);
 
5257
}
 
5258
 
 
5259
 
 
5260
/**
 
5261
  This function is only called during parsing. We will signal an error if
 
5262
  value is not a true double value (overflow)
 
5263
*/
 
5264
 
 
5265
Item_float::Item_float(const char *str_arg, uint length)
 
5266
{
 
5267
  int error;
 
5268
  char *end_not_used;
 
5269
  value= my_strntod(&my_charset_bin, (char*) str_arg, length, &end_not_used,
 
5270
                    &error);
 
5271
  if (error)
 
5272
  {
 
5273
    /*
 
5274
      Note that we depend on that str_arg is null terminated, which is true
 
5275
      when we are in the parser
 
5276
    */
 
5277
    DBUG_ASSERT(str_arg[length] == 0);
 
5278
    my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", (char*) str_arg);
 
5279
  }
 
5280
  presentation= name=(char*) str_arg;
 
5281
  decimals=(uint8) nr_of_decimals(str_arg, str_arg+length);
 
5282
  max_length=length;
 
5283
  fixed= 1;
 
5284
}
 
5285
 
 
5286
 
 
5287
int Item_float::save_in_field(Field *field, bool no_conversions)
 
5288
{
 
5289
  double nr= val_real();
 
5290
  if (null_value)
 
5291
    return set_field_to_null(field);
 
5292
  field->set_notnull();
 
5293
  return field->store(nr);
 
5294
}
 
5295
 
 
5296
 
 
5297
void Item_float::print(String *str, enum_query_type query_type)
 
5298
{
 
5299
  if (presentation)
 
5300
  {
 
5301
    str->append(presentation);
 
5302
    return;
 
5303
  }
 
5304
  char buffer[20];
 
5305
  String num(buffer, sizeof(buffer), &my_charset_bin);
 
5306
  num.set_real(value, decimals, &my_charset_bin);
 
5307
  str->append(num);
 
5308
}
 
5309
 
 
5310
 
 
5311
/*
 
5312
  hex item
 
5313
  In string context this is a binary string.
 
5314
  In number context this is a longlong value.
 
5315
*/
 
5316
 
 
5317
bool Item_float::eq(const Item *arg, bool binary_cmp) const
 
5318
{
 
5319
  if (arg->basic_const_item() && arg->type() == type())
 
5320
  {
 
5321
    /*
 
5322
      We need to cast off const to call val_int(). This should be OK for
 
5323
      a basic constant.
 
5324
    */
 
5325
    Item *item= (Item*) arg;
 
5326
    return item->val_real() == value;
 
5327
  }
 
5328
  return FALSE;
 
5329
}
 
5330
 
 
5331
 
 
5332
inline uint char_val(char X)
 
5333
{
 
5334
  return (uint) (X >= '0' && X <= '9' ? X-'0' :
 
5335
                 X >= 'A' && X <= 'Z' ? X-'A'+10 :
 
5336
                 X-'a'+10);
 
5337
}
 
5338
 
 
5339
 
 
5340
Item_hex_string::Item_hex_string(const char *str, uint str_length)
 
5341
{
 
5342
  max_length=(str_length+1)/2;
 
5343
  char *ptr=(char*) sql_alloc(max_length+1);
 
5344
  if (!ptr)
 
5345
    return;
 
5346
  str_value.set(ptr,max_length,&my_charset_bin);
 
5347
  char *end=ptr+max_length;
 
5348
  if (max_length*2 != str_length)
 
5349
    *ptr++=char_val(*str++);                    // Not even, assume 0 prefix
 
5350
  while (ptr != end)
 
5351
  {
 
5352
    *ptr++= (char) (char_val(str[0])*16+char_val(str[1]));
 
5353
    str+=2;
 
5354
  }
 
5355
  *ptr=0;                                       // Keep purify happy
 
5356
  collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
 
5357
  fixed= 1;
 
5358
  unsigned_flag= 1;
 
5359
}
 
5360
 
 
5361
longlong Item_hex_string::val_int()
 
5362
{
 
5363
  // following assert is redundant, because fixed=1 assigned in constructor
 
5364
  DBUG_ASSERT(fixed == 1);
 
5365
  char *end=(char*) str_value.ptr()+str_value.length(),
 
5366
       *ptr=end-min(str_value.length(),sizeof(longlong));
 
5367
 
 
5368
  ulonglong value=0;
 
5369
  for (; ptr != end ; ptr++)
 
5370
    value=(value << 8)+ (ulonglong) (uchar) *ptr;
 
5371
  return (longlong) value;
 
5372
}
 
5373
 
 
5374
 
 
5375
my_decimal *Item_hex_string::val_decimal(my_decimal *decimal_value)
 
5376
{
 
5377
  // following assert is redundant, because fixed=1 assigned in constructor
 
5378
  DBUG_ASSERT(fixed == 1);
 
5379
  ulonglong value= (ulonglong)val_int();
 
5380
  int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value);
 
5381
  return (decimal_value);
 
5382
}
 
5383
 
 
5384
 
 
5385
int Item_hex_string::save_in_field(Field *field, bool no_conversions)
 
5386
{
 
5387
  field->set_notnull();
 
5388
  if (field->result_type() == STRING_RESULT)
 
5389
    return field->store(str_value.ptr(), str_value.length(), 
 
5390
                        collation.collation);
 
5391
 
 
5392
  ulonglong nr;
 
5393
  uint32 length= str_value.length();
 
5394
  if (!length)
 
5395
    return 1;
 
5396
 
 
5397
  if (length > 8)
 
5398
  {
 
5399
    nr= field->flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX;
 
5400
    goto warn;
 
5401
  }
 
5402
  nr= (ulonglong) val_int();
 
5403
  if ((length == 8) && !(field->flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX))
 
5404
  {
 
5405
    nr= LONGLONG_MAX;
 
5406
    goto warn;
 
5407
  }
 
5408
  return field->store((longlong) nr, TRUE);  // Assume hex numbers are unsigned
 
5409
 
 
5410
warn:
 
5411
  if (!field->store((longlong) nr, TRUE))
 
5412
    field->set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE,
 
5413
                       1);
 
5414
  return 1;
 
5415
}
 
5416
 
 
5417
 
 
5418
void Item_hex_string::print(String *str, enum_query_type query_type)
 
5419
{
 
5420
  char *end= (char*) str_value.ptr() + str_value.length(),
 
5421
       *ptr= end - min(str_value.length(), sizeof(longlong));
 
5422
  str->append("0x");
 
5423
  for (; ptr != end ; ptr++)
 
5424
  {
 
5425
    str->append(_dig_vec_lower[((uchar) *ptr) >> 4]);
 
5426
    str->append(_dig_vec_lower[((uchar) *ptr) & 0x0F]);
 
5427
  }
 
5428
}
 
5429
 
 
5430
 
 
5431
bool Item_hex_string::eq(const Item *arg, bool binary_cmp) const
 
5432
{
 
5433
  if (arg->basic_const_item() && arg->type() == type())
 
5434
  {
 
5435
    if (binary_cmp)
 
5436
      return !stringcmp(&str_value, &arg->str_value);
 
5437
    return !sortcmp(&str_value, &arg->str_value, collation.collation);
 
5438
  }
 
5439
  return FALSE;
 
5440
}
 
5441
 
 
5442
 
 
5443
Item *Item_hex_string::safe_charset_converter(CHARSET_INFO *tocs)
 
5444
{
 
5445
  Item_string *conv;
 
5446
  String tmp, *str= val_str(&tmp);
 
5447
 
 
5448
  if (!(conv= new Item_string(str->ptr(), str->length(), tocs)))
 
5449
    return NULL;
 
5450
  conv->str_value.copy();
 
5451
  conv->str_value.mark_as_const();
 
5452
  return conv;
 
5453
}
 
5454
 
 
5455
 
 
5456
/*
 
5457
  bin item.
 
5458
  In string context this is a binary string.
 
5459
  In number context this is a longlong value.
 
5460
*/
 
5461
  
 
5462
Item_bin_string::Item_bin_string(const char *str, uint str_length)
 
5463
{
 
5464
  const char *end= str + str_length - 1;
 
5465
  uchar bits= 0;
 
5466
  uint power= 1;
 
5467
 
 
5468
  max_length= (str_length + 7) >> 3;
 
5469
  char *ptr= (char*) sql_alloc(max_length + 1);
 
5470
  if (!ptr)
 
5471
    return;
 
5472
  str_value.set(ptr, max_length, &my_charset_bin);
 
5473
 
 
5474
  if (max_length > 0)
 
5475
  {
 
5476
    ptr+= max_length - 1;
 
5477
    ptr[1]= 0;                     // Set end null for string
 
5478
    for (; end >= str; end--)
 
5479
    {
 
5480
      if (power == 256)
 
5481
      {
 
5482
        power= 1;
 
5483
        *ptr--= bits;
 
5484
        bits= 0;
 
5485
      }
 
5486
      if (*end == '1')
 
5487
        bits|= power;
 
5488
      power<<= 1;
 
5489
    }
 
5490
    *ptr= (char) bits;
 
5491
  }
 
5492
  else
 
5493
    ptr[0]= 0;
 
5494
 
 
5495
  collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
 
5496
  fixed= 1;
 
5497
}
 
5498
 
 
5499
 
 
5500
/**
 
5501
  Pack data in buffer for sending.
 
5502
*/
 
5503
 
 
5504
bool Item_null::send(Protocol *protocol, String *packet)
 
5505
{
 
5506
  return protocol->store_null();
 
5507
}
 
5508
 
 
5509
/**
 
5510
  This is only called from items that is not of type item_field.
 
5511
*/
 
5512
 
 
5513
bool Item::send(Protocol *protocol, String *buffer)
 
5514
{
 
5515
  bool UNINIT_VAR(result);                       // Will be set if null_value == 0
 
5516
  enum_field_types f_type;
 
5517
 
 
5518
  switch ((f_type=field_type())) {
 
5519
  default:
 
5520
  case MYSQL_TYPE_NULL:
 
5521
  case MYSQL_TYPE_DECIMAL:
 
5522
  case MYSQL_TYPE_ENUM:
 
5523
  case MYSQL_TYPE_SET:
 
5524
  case MYSQL_TYPE_TINY_BLOB:
 
5525
  case MYSQL_TYPE_MEDIUM_BLOB:
 
5526
  case MYSQL_TYPE_LONG_BLOB:
 
5527
  case MYSQL_TYPE_BLOB:
 
5528
  case MYSQL_TYPE_GEOMETRY:
 
5529
  case MYSQL_TYPE_STRING:
 
5530
  case MYSQL_TYPE_VAR_STRING:
 
5531
  case MYSQL_TYPE_VARCHAR:
 
5532
  case MYSQL_TYPE_BIT:
 
5533
  case MYSQL_TYPE_NEWDECIMAL:
 
5534
  {
 
5535
    String *res;
 
5536
    if ((res=val_str(buffer)))
 
5537
      result= protocol->store(res->ptr(),res->length(),res->charset());
 
5538
    break;
 
5539
  }
 
5540
  case MYSQL_TYPE_TINY:
 
5541
  {
 
5542
    longlong nr;
 
5543
    nr= val_int();
 
5544
    if (!null_value)
 
5545
      result= protocol->store_tiny(nr);
 
5546
    break;
 
5547
  }
 
5548
  case MYSQL_TYPE_SHORT:
 
5549
  case MYSQL_TYPE_YEAR:
 
5550
  {
 
5551
    longlong nr;
 
5552
    nr= val_int();
 
5553
    if (!null_value)
 
5554
      result= protocol->store_short(nr);
 
5555
    break;
 
5556
  }
 
5557
  case MYSQL_TYPE_INT24:
 
5558
  case MYSQL_TYPE_LONG:
 
5559
  {
 
5560
    longlong nr;
 
5561
    nr= val_int();
 
5562
    if (!null_value)
 
5563
      result= protocol->store_long(nr);
 
5564
    break;
 
5565
  }
 
5566
  case MYSQL_TYPE_LONGLONG:
 
5567
  {
 
5568
    longlong nr;
 
5569
    nr= val_int();
 
5570
    if (!null_value)
 
5571
      result= protocol->store_longlong(nr, unsigned_flag);
 
5572
    break;
 
5573
  }
 
5574
  case MYSQL_TYPE_FLOAT:
 
5575
  {
 
5576
    float nr;
 
5577
    nr= (float) val_real();
 
5578
    if (!null_value)
 
5579
      result= protocol->store(nr, decimals, buffer);
 
5580
    break;
 
5581
  }
 
5582
  case MYSQL_TYPE_DOUBLE:
 
5583
  {
 
5584
    double nr= val_real();
 
5585
    if (!null_value)
 
5586
      result= protocol->store(nr, decimals, buffer);
 
5587
    break;
 
5588
  }
 
5589
  case MYSQL_TYPE_DATETIME:
 
5590
  case MYSQL_TYPE_DATE:
 
5591
  case MYSQL_TYPE_TIMESTAMP:
 
5592
  {
 
5593
    MYSQL_TIME tm;
 
5594
    get_date(&tm, TIME_FUZZY_DATE);
 
5595
    if (!null_value)
 
5596
    {
 
5597
      if (f_type == MYSQL_TYPE_DATE)
 
5598
        return protocol->store_date(&tm);
 
5599
      else
 
5600
        result= protocol->store(&tm);
 
5601
    }
 
5602
    break;
 
5603
  }
 
5604
  case MYSQL_TYPE_TIME:
 
5605
  {
 
5606
    MYSQL_TIME tm;
 
5607
    get_time(&tm);
 
5608
    if (!null_value)
 
5609
      result= protocol->store_time(&tm);
 
5610
    break;
 
5611
  }
 
5612
  }
 
5613
  if (null_value)
 
5614
    result= protocol->store_null();
 
5615
  return result;
 
5616
}
 
5617
 
 
5618
 
 
5619
bool Item_field::send(Protocol *protocol, String *buffer)
 
5620
{
 
5621
  return protocol->store(result_field);
 
5622
}
 
5623
 
 
5624
 
 
5625
void Item_field::update_null_value() 
 
5626
 
5627
  /* 
 
5628
    need to set no_errors to prevent warnings about type conversion 
 
5629
    popping up.
 
5630
  */
 
5631
  THD *thd= field->table->in_use;
 
5632
  int no_errors;
 
5633
 
 
5634
  no_errors= thd->no_errors;
 
5635
  thd->no_errors= 1;
 
5636
  Item::update_null_value();
 
5637
  thd->no_errors= no_errors;
 
5638
}
 
5639
 
 
5640
 
 
5641
/*
 
5642
  Add the field to the select list and substitute it for the reference to
 
5643
  the field.
 
5644
 
 
5645
  SYNOPSIS
 
5646
    Item_field::update_value_transformer()
 
5647
    select_arg      current select
 
5648
 
 
5649
  DESCRIPTION
 
5650
    If the field doesn't belong to the table being inserted into then it is
 
5651
    added to the select list, pointer to it is stored in the ref_pointer_array
 
5652
    of the select and the field itself is substituted for the Item_ref object.
 
5653
    This is done in order to get correct values from update fields that
 
5654
    belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY
 
5655
    UPDATE statement.
 
5656
 
 
5657
  RETURN
 
5658
    0             if error occured
 
5659
    ref           if all conditions are met
 
5660
    this field    otherwise
 
5661
*/
 
5662
 
 
5663
Item *Item_field::update_value_transformer(uchar *select_arg)
 
5664
{
 
5665
  SELECT_LEX *select= (SELECT_LEX*)select_arg;
 
5666
  DBUG_ASSERT(fixed);
 
5667
 
 
5668
  if (field->table != select->context.table_list->table &&
 
5669
      type() != Item::TRIGGER_FIELD_ITEM)
 
5670
  {
 
5671
    List<Item> *all_fields= &select->join->all_fields;
 
5672
    Item **ref_pointer_array= select->ref_pointer_array;
 
5673
    int el= all_fields->elements;
 
5674
    Item_ref *ref;
 
5675
 
 
5676
    ref_pointer_array[el]= (Item*)this;
 
5677
    all_fields->push_front((Item*)this);
 
5678
    ref= new Item_ref(&select->context, ref_pointer_array + el,
 
5679
                      table_name, field_name);
 
5680
    return ref;
 
5681
  }
 
5682
  return this;
 
5683
}
 
5684
 
 
5685
 
 
5686
void Item_field::print(String *str, enum_query_type query_type)
 
5687
{
 
5688
  if (field && field->table->const_table)
 
5689
  {
 
5690
    char buff[MAX_FIELD_WIDTH];
 
5691
    String tmp(buff,sizeof(buff),str->charset());
 
5692
    field->val_str(&tmp);
 
5693
    str->append('\'');
 
5694
    str->append(tmp);
 
5695
    str->append('\'');
 
5696
    return;
 
5697
  }
 
5698
  Item_ident::print(str, query_type);
 
5699
}
 
5700
 
 
5701
 
 
5702
Item_ref::Item_ref(Name_resolution_context *context_arg,
 
5703
                   Item **item, const char *table_name_arg,
 
5704
                   const char *field_name_arg,
 
5705
                   bool alias_name_used_arg)
 
5706
  :Item_ident(context_arg, NullS, table_name_arg, field_name_arg),
 
5707
   result_field(0), ref(item)
 
5708
{
 
5709
  alias_name_used= alias_name_used_arg;
 
5710
  /*
 
5711
    This constructor used to create some internals references over fixed items
 
5712
  */
 
5713
  if (ref && *ref && (*ref)->fixed)
 
5714
    set_properties();
 
5715
}
 
5716
 
 
5717
 
 
5718
/**
 
5719
  Resolve the name of a reference to a column reference.
 
5720
 
 
5721
  The method resolves the column reference represented by 'this' as a column
 
5722
  present in one of: GROUP BY clause, SELECT clause, outer queries. It is
 
5723
  used typically for columns in the HAVING clause which are not under
 
5724
  aggregate functions.
 
5725
 
 
5726
  POSTCONDITION @n
 
5727
  Item_ref::ref is 0 or points to a valid item.
 
5728
 
 
5729
  @note
 
5730
    The name resolution algorithm used is (where [T_j] is an optional table
 
5731
    name that qualifies the column name):
 
5732
 
 
5733
  @code
 
5734
        resolve_extended([T_j].col_ref_i)
 
5735
        {
 
5736
          Search for a column or derived column named col_ref_i [in table T_j]
 
5737
          in the SELECT and GROUP clauses of Q.
 
5738
 
 
5739
          if such a column is NOT found AND    // Lookup in outer queries.
 
5740
             there are outer queries
 
5741
          {
 
5742
            for each outer query Q_k beginning from the inner-most one
 
5743
           {
 
5744
              Search for a column or derived column named col_ref_i
 
5745
              [in table T_j] in the SELECT and GROUP clauses of Q_k.
 
5746
 
 
5747
              if such a column is not found AND
 
5748
                 - Q_k is not a group query AND
 
5749
                 - Q_k is not inside an aggregate function
 
5750
                 OR
 
5751
                 - Q_(k-1) is not in a HAVING or SELECT clause of Q_k
 
5752
              {
 
5753
                search for a column or derived column named col_ref_i
 
5754
                [in table T_j] in the FROM clause of Q_k;
 
5755
              }
 
5756
            }
 
5757
          }
 
5758
        }
 
5759
  @endcode
 
5760
  @n
 
5761
    This procedure treats GROUP BY and SELECT clauses as one namespace for
 
5762
    column references in HAVING. Notice that compared to
 
5763
    Item_field::fix_fields, here we first search the SELECT and GROUP BY
 
5764
    clauses, and then we search the FROM clause.
 
5765
 
 
5766
  @param[in]     thd        current thread
 
5767
  @param[in,out] reference  view column if this item was resolved to a
 
5768
    view column
 
5769
 
 
5770
  @todo
 
5771
    Here we could first find the field anyway, and then test this
 
5772
    condition, so that we can give a better error message -
 
5773
    ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
 
5774
    ER_BAD_FIELD_ERROR which we produce now.
 
5775
 
 
5776
  @retval
 
5777
    TRUE  if error
 
5778
  @retval
 
5779
    FALSE on success
 
5780
*/
 
5781
 
 
5782
bool Item_ref::fix_fields(THD *thd, Item **reference)
 
5783
{
 
5784
  enum_parsing_place place= NO_MATTER;
 
5785
  DBUG_ASSERT(fixed == 0);
 
5786
  SELECT_LEX *current_sel= thd->lex->current_select;
 
5787
 
 
5788
  if (!ref || ref == not_found_item)
 
5789
  {
 
5790
    if (!(ref= resolve_ref_in_select_and_group(thd, this,
 
5791
                                               context->select_lex)))
 
5792
      goto error;             /* Some error occurred (e.g. ambiguous names). */
 
5793
 
 
5794
    if (ref == not_found_item) /* This reference was not resolved. */
 
5795
    {
 
5796
      Name_resolution_context *last_checked_context= context;
 
5797
      Name_resolution_context *outer_context= context->outer_context;
 
5798
      Field *from_field;
 
5799
      ref= 0;
 
5800
 
 
5801
      if (!outer_context)
 
5802
      {
 
5803
        /* The current reference cannot be resolved in this query. */
 
5804
        my_error(ER_BAD_FIELD_ERROR,MYF(0),
 
5805
                 this->full_name(), current_thd->where);
 
5806
        goto error;
 
5807
      }
 
5808
 
 
5809
      /*
 
5810
        If there is an outer context (select), and it is not a derived table
 
5811
        (which do not support the use of outer fields for now), try to
 
5812
        resolve this reference in the outer select(s).
 
5813
 
 
5814
        We treat each subselect as a separate namespace, so that different
 
5815
        subselects may contain columns with the same names. The subselects are
 
5816
        searched starting from the innermost.
 
5817
      */
 
5818
      from_field= (Field*) not_found_field;
 
5819
 
 
5820
      do
 
5821
      {
 
5822
        SELECT_LEX *select= outer_context->select_lex;
 
5823
        Item_subselect *prev_subselect_item=
 
5824
          last_checked_context->select_lex->master_unit()->item;
 
5825
        last_checked_context= outer_context;
 
5826
 
 
5827
        /* Search in the SELECT and GROUP lists of the outer select. */
 
5828
        if (outer_context->resolve_in_select_list)
 
5829
        {
 
5830
          if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
 
5831
            goto error; /* Some error occurred (e.g. ambiguous names). */
 
5832
          if (ref != not_found_item)
 
5833
          {
 
5834
            DBUG_ASSERT(*ref && (*ref)->fixed);
 
5835
            prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
 
5836
            prev_subselect_item->const_item_cache&= (*ref)->const_item();
 
5837
            break;
 
5838
          }
 
5839
          /*
 
5840
            Set ref to 0 to ensure that we get an error in case we replaced
 
5841
            this item with another item and still use this item in some
 
5842
            other place of the parse tree.
 
5843
          */
 
5844
          ref= 0;
 
5845
        }
 
5846
 
 
5847
        place= prev_subselect_item->parsing_place;
 
5848
        /*
 
5849
          Check table fields only if the subquery is used somewhere out of
 
5850
          HAVING or the outer SELECT does not use grouping (i.e. tables are
 
5851
          accessible).
 
5852
          TODO:
 
5853
          Here we could first find the field anyway, and then test this
 
5854
          condition, so that we can give a better error message -
 
5855
          ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
 
5856
          ER_BAD_FIELD_ERROR which we produce now.
 
5857
        */
 
5858
        if ((place != IN_HAVING ||
 
5859
             (!select->with_sum_func &&
 
5860
              select->group_list.elements == 0)))
 
5861
        {
 
5862
          /*
 
5863
            In case of view, find_field_in_tables() write pointer to view
 
5864
            field expression to 'reference', i.e. it substitute that
 
5865
            expression instead of this Item_ref
 
5866
          */
 
5867
          from_field= find_field_in_tables(thd, this,
 
5868
                                           outer_context->
 
5869
                                             first_name_resolution_table,
 
5870
                                           outer_context->
 
5871
                                             last_name_resolution_table,
 
5872
                                           reference,
 
5873
                                           IGNORE_EXCEPT_NON_UNIQUE,
 
5874
                                           TRUE, TRUE);
 
5875
          if (! from_field)
 
5876
            goto error;
 
5877
          if (from_field == view_ref_found)
 
5878
          {
 
5879
            Item::Type refer_type= (*reference)->type();
 
5880
            prev_subselect_item->used_tables_cache|=
 
5881
              (*reference)->used_tables();
 
5882
            prev_subselect_item->const_item_cache&=
 
5883
              (*reference)->const_item();
 
5884
            DBUG_ASSERT((*reference)->type() == REF_ITEM);
 
5885
            mark_as_dependent(thd, last_checked_context->select_lex,
 
5886
                              context->select_lex, this,
 
5887
                              ((refer_type == REF_ITEM ||
 
5888
                                refer_type == FIELD_ITEM) ?
 
5889
                               (Item_ident*) (*reference) :
 
5890
                               0));
 
5891
            /*
 
5892
              view reference found, we substituted it instead of this
 
5893
              Item, so can quit
 
5894
            */
 
5895
            return FALSE;
 
5896
          }
 
5897
          if (from_field != not_found_field)
 
5898
          {
 
5899
            if (cached_table && cached_table->select_lex &&
 
5900
                outer_context->select_lex &&
 
5901
                cached_table->select_lex != outer_context->select_lex)
 
5902
            {
 
5903
              /*
 
5904
                Due to cache, find_field_in_tables() can return field which
 
5905
                doesn't belong to provided outer_context. In this case we have
 
5906
                to find proper field context in order to fix field correcly.
 
5907
              */
 
5908
              do
 
5909
              {
 
5910
                outer_context= outer_context->outer_context;
 
5911
                select= outer_context->select_lex;
 
5912
                prev_subselect_item=
 
5913
                  last_checked_context->select_lex->master_unit()->item;
 
5914
                last_checked_context= outer_context;
 
5915
              } while (outer_context && outer_context->select_lex &&
 
5916
                       cached_table->select_lex != outer_context->select_lex);
 
5917
            }
 
5918
            prev_subselect_item->used_tables_cache|= from_field->table->map;
 
5919
            prev_subselect_item->const_item_cache= 0;
 
5920
            break;
 
5921
          }
 
5922
        }
 
5923
        DBUG_ASSERT(from_field == not_found_field);
 
5924
 
 
5925
        /* Reference is not found => depend on outer (or just error). */
 
5926
        prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
 
5927
        prev_subselect_item->const_item_cache= 0;
 
5928
 
 
5929
        outer_context= outer_context->outer_context;
 
5930
      } while (outer_context);
 
5931
 
 
5932
      DBUG_ASSERT(from_field != 0 && from_field != view_ref_found);
 
5933
      if (from_field != not_found_field)
 
5934
      {
 
5935
        Item_field* fld;
 
5936
        if (!(fld= new Item_field(from_field)))
 
5937
          goto error;
 
5938
        thd->change_item_tree(reference, fld);
 
5939
        mark_as_dependent(thd, last_checked_context->select_lex,
 
5940
                          thd->lex->current_select, this, fld);
 
5941
        /*
 
5942
          A reference is resolved to a nest level that's outer or the same as
 
5943
          the nest level of the enclosing set function : adjust the value of
 
5944
          max_arg_level for the function if it's needed.
 
5945
        */
 
5946
        if (thd->lex->in_sum_func &&
 
5947
            thd->lex->in_sum_func->nest_level >= 
 
5948
            last_checked_context->select_lex->nest_level)
 
5949
          set_if_bigger(thd->lex->in_sum_func->max_arg_level,
 
5950
                        last_checked_context->select_lex->nest_level);
 
5951
        return FALSE;
 
5952
      }
 
5953
      if (ref == 0)
 
5954
      {
 
5955
        /* The item was not a table field and not a reference */
 
5956
        my_error(ER_BAD_FIELD_ERROR, MYF(0),
 
5957
                 this->full_name(), current_thd->where);
 
5958
        goto error;
 
5959
      }
 
5960
      /* Should be checked in resolve_ref_in_select_and_group(). */
 
5961
      DBUG_ASSERT(*ref && (*ref)->fixed);
 
5962
      mark_as_dependent(thd, last_checked_context->select_lex,
 
5963
                        context->select_lex, this, this);
 
5964
      /*
 
5965
        A reference is resolved to a nest level that's outer or the same as
 
5966
        the nest level of the enclosing set function : adjust the value of
 
5967
        max_arg_level for the function if it's needed.
 
5968
      */
 
5969
      if (thd->lex->in_sum_func &&
 
5970
          thd->lex->in_sum_func->nest_level >= 
 
5971
          last_checked_context->select_lex->nest_level)
 
5972
        set_if_bigger(thd->lex->in_sum_func->max_arg_level,
 
5973
                      last_checked_context->select_lex->nest_level);
 
5974
    }
 
5975
  }
 
5976
 
 
5977
  DBUG_ASSERT(*ref);
 
5978
  /*
 
5979
    Check if this is an incorrect reference in a group function or forward
 
5980
    reference. Do not issue an error if this is:
 
5981
      1. outer reference (will be fixed later by the fix_inner_refs function);
 
5982
      2. an unnamed reference inside an aggregate function.
 
5983
  */
 
5984
  if (!((*ref)->type() == REF_ITEM &&
 
5985
       ((Item_ref *)(*ref))->ref_type() == OUTER_REF) &&
 
5986
      (((*ref)->with_sum_func && name &&
 
5987
        !(current_sel->linkage != GLOBAL_OPTIONS_TYPE &&
 
5988
          current_sel->having_fix_field)) ||
 
5989
       !(*ref)->fixed))
 
5990
  {
 
5991
    my_error(ER_ILLEGAL_REFERENCE, MYF(0),
 
5992
             name, ((*ref)->with_sum_func?
 
5993
                    "reference to group function":
 
5994
                    "forward reference in item list"));
 
5995
    goto error;
 
5996
  }
 
5997
 
 
5998
  set_properties();
 
5999
 
 
6000
  if ((*ref)->check_cols(1))
 
6001
    goto error;
 
6002
  return FALSE;
 
6003
 
 
6004
error:
 
6005
  context->process_error(thd);
 
6006
  return TRUE;
 
6007
}
 
6008
 
 
6009
 
 
6010
void Item_ref::set_properties()
 
6011
{
 
6012
  max_length= (*ref)->max_length;
 
6013
  maybe_null= (*ref)->maybe_null;
 
6014
  decimals=   (*ref)->decimals;
 
6015
  collation.set((*ref)->collation);
 
6016
  /*
 
6017
    We have to remember if we refer to a sum function, to ensure that
 
6018
    split_sum_func() doesn't try to change the reference.
 
6019
  */
 
6020
  with_sum_func= (*ref)->with_sum_func;
 
6021
  unsigned_flag= (*ref)->unsigned_flag;
 
6022
  fixed= 1;
 
6023
  if (alias_name_used)
 
6024
    return;
 
6025
  if ((*ref)->type() == FIELD_ITEM)
 
6026
    alias_name_used= ((Item_ident *) (*ref))->alias_name_used;
 
6027
  else
 
6028
    alias_name_used= TRUE; // it is not field, so it is was resolved by alias
 
6029
}
 
6030
 
 
6031
 
 
6032
void Item_ref::cleanup()
 
6033
{
 
6034
  DBUG_ENTER("Item_ref::cleanup");
 
6035
  Item_ident::cleanup();
 
6036
  result_field= 0;
 
6037
  DBUG_VOID_RETURN;
 
6038
}
 
6039
 
 
6040
 
 
6041
void Item_ref::print(String *str, enum_query_type query_type)
 
6042
{
 
6043
  if (ref)
 
6044
  {
 
6045
    if ((*ref)->type() != Item::CACHE_ITEM && ref_type() != VIEW_REF &&
 
6046
        !table_name && name && alias_name_used)
 
6047
    {
 
6048
      THD *thd= current_thd;
 
6049
      append_identifier(thd, str, (*ref)->real_item()->name,
 
6050
                        (*ref)->real_item()->name_length);
 
6051
    }
 
6052
    else
 
6053
      (*ref)->print(str, query_type);
 
6054
  }
 
6055
  else
 
6056
    Item_ident::print(str, query_type);
 
6057
}
 
6058
 
 
6059
 
 
6060
bool Item_ref::send(Protocol *prot, String *tmp)
 
6061
{
 
6062
  if (result_field)
 
6063
    return prot->store(result_field);
 
6064
  return (*ref)->send(prot, tmp);
 
6065
}
 
6066
 
 
6067
 
 
6068
double Item_ref::val_result()
 
6069
{
 
6070
  if (result_field)
 
6071
  {
 
6072
    if ((null_value= result_field->is_null()))
 
6073
      return 0.0;
 
6074
    return result_field->val_real();
 
6075
  }
 
6076
  return val_real();
 
6077
}
 
6078
 
 
6079
 
 
6080
bool Item_ref::is_null_result()
 
6081
{
 
6082
  if (result_field)
 
6083
    return (null_value=result_field->is_null());
 
6084
 
 
6085
  return is_null();
 
6086
}
 
6087
 
 
6088
 
 
6089
longlong Item_ref::val_int_result()
 
6090
{
 
6091
  if (result_field)
 
6092
  {
 
6093
    if ((null_value= result_field->is_null()))
 
6094
      return 0;
 
6095
    return result_field->val_int();
 
6096
  }
 
6097
  return val_int();
 
6098
}
 
6099
 
 
6100
 
 
6101
String *Item_ref::str_result(String* str)
 
6102
{
 
6103
  if (result_field)
 
6104
  {
 
6105
    if ((null_value= result_field->is_null()))
 
6106
      return 0;
 
6107
    str->set_charset(str_value.charset());
 
6108
    return result_field->val_str(str, &str_value);
 
6109
  }
 
6110
  return val_str(str);
 
6111
}
 
6112
 
 
6113
 
 
6114
my_decimal *Item_ref::val_decimal_result(my_decimal *decimal_value)
 
6115
{
 
6116
  if (result_field)
 
6117
  {
 
6118
    if ((null_value= result_field->is_null()))
 
6119
      return 0;
 
6120
    return result_field->val_decimal(decimal_value);
 
6121
  }
 
6122
  return val_decimal(decimal_value);
 
6123
}
 
6124
 
 
6125
 
 
6126
bool Item_ref::val_bool_result()
 
6127
{
 
6128
  if (result_field)
 
6129
  {
 
6130
    if ((null_value= result_field->is_null()))
 
6131
      return 0;
 
6132
    switch (result_field->result_type()) {
 
6133
    case INT_RESULT:
 
6134
      return result_field->val_int() != 0;
 
6135
    case DECIMAL_RESULT:
 
6136
    {
 
6137
      my_decimal decimal_value;
 
6138
      my_decimal *val= result_field->val_decimal(&decimal_value);
 
6139
      if (val)
 
6140
        return !my_decimal_is_zero(val);
 
6141
      return 0;
 
6142
    }
 
6143
    case REAL_RESULT:
 
6144
    case STRING_RESULT:
 
6145
      return result_field->val_real() != 0.0;
 
6146
    case ROW_RESULT:
 
6147
    default:
 
6148
      DBUG_ASSERT(0);
 
6149
    }
 
6150
  }
 
6151
  return val_bool();
 
6152
}
 
6153
 
 
6154
 
 
6155
double Item_ref::val_real()
 
6156
{
 
6157
  DBUG_ASSERT(fixed);
 
6158
  double tmp=(*ref)->val_result();
 
6159
  null_value=(*ref)->null_value;
 
6160
  return tmp;
 
6161
}
 
6162
 
 
6163
 
 
6164
longlong Item_ref::val_int()
 
6165
{
 
6166
  DBUG_ASSERT(fixed);
 
6167
  longlong tmp=(*ref)->val_int_result();
 
6168
  null_value=(*ref)->null_value;
 
6169
  return tmp;
 
6170
}
 
6171
 
 
6172
 
 
6173
bool Item_ref::val_bool()
 
6174
{
 
6175
  DBUG_ASSERT(fixed);
 
6176
  bool tmp= (*ref)->val_bool_result();
 
6177
  null_value= (*ref)->null_value;
 
6178
  return tmp;
 
6179
}
 
6180
 
 
6181
 
 
6182
String *Item_ref::val_str(String* tmp)
 
6183
{
 
6184
  DBUG_ASSERT(fixed);
 
6185
  tmp=(*ref)->str_result(tmp);
 
6186
  null_value=(*ref)->null_value;
 
6187
  return tmp;
 
6188
}
 
6189
 
 
6190
 
 
6191
bool Item_ref::is_null()
 
6192
{
 
6193
  DBUG_ASSERT(fixed);
 
6194
  bool tmp=(*ref)->is_null_result();
 
6195
  null_value=(*ref)->null_value;
 
6196
  return tmp;
 
6197
}
 
6198
 
 
6199
 
 
6200
bool Item_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
 
6201
{
 
6202
  return (null_value=(*ref)->get_date_result(ltime,fuzzydate));
 
6203
}
 
6204
 
 
6205
 
 
6206
my_decimal *Item_ref::val_decimal(my_decimal *decimal_value)
 
6207
{
 
6208
  my_decimal *val= (*ref)->val_decimal_result(decimal_value);
 
6209
  null_value= (*ref)->null_value;
 
6210
  return val;
 
6211
}
 
6212
 
 
6213
int Item_ref::save_in_field(Field *to, bool no_conversions)
 
6214
{
 
6215
  int res;
 
6216
  DBUG_ASSERT(!result_field);
 
6217
  res= (*ref)->save_in_field(to, no_conversions);
 
6218
  null_value= (*ref)->null_value;
 
6219
  return res;
 
6220
}
 
6221
 
 
6222
 
 
6223
void Item_ref::save_org_in_field(Field *field)
 
6224
{
 
6225
  (*ref)->save_org_in_field(field);
 
6226
}
 
6227
 
 
6228
 
 
6229
void Item_ref::make_field(Send_field *field)
 
6230
{
 
6231
  (*ref)->make_field(field);
 
6232
  /* Non-zero in case of a view */
 
6233
  if (name)
 
6234
    field->col_name= name;
 
6235
  if (table_name)
 
6236
    field->table_name= table_name;
 
6237
  if (db_name)
 
6238
    field->db_name= db_name;
 
6239
  if (orig_field_name)
 
6240
    field->org_col_name= orig_field_name;
 
6241
  if (orig_table_name)
 
6242
    field->org_table_name= orig_table_name;
 
6243
}
 
6244
 
 
6245
 
 
6246
Item *Item_ref::get_tmp_table_item(THD *thd)
 
6247
{
 
6248
  if (!result_field)
 
6249
    return (*ref)->get_tmp_table_item(thd);
 
6250
 
 
6251
  Item_field *item= new Item_field(result_field);
 
6252
  if (item)
 
6253
  {
 
6254
    item->table_name= table_name;
 
6255
    item->db_name= db_name;
 
6256
  }
 
6257
  return item;
 
6258
}
 
6259
 
 
6260
 
 
6261
void Item_ref_null_helper::print(String *str, enum_query_type query_type)
 
6262
{
 
6263
  str->append(STRING_WITH_LEN("<ref_null_helper>("));
 
6264
  if (ref)
 
6265
    (*ref)->print(str, query_type);
 
6266
  else
 
6267
    str->append('?');
 
6268
  str->append(')');
 
6269
}
 
6270
 
 
6271
 
 
6272
double Item_direct_ref::val_real()
 
6273
{
 
6274
  double tmp=(*ref)->val_real();
 
6275
  null_value=(*ref)->null_value;
 
6276
  return tmp;
 
6277
}
 
6278
 
 
6279
 
 
6280
longlong Item_direct_ref::val_int()
 
6281
{
 
6282
  longlong tmp=(*ref)->val_int();
 
6283
  null_value=(*ref)->null_value;
 
6284
  return tmp;
 
6285
}
 
6286
 
 
6287
 
 
6288
String *Item_direct_ref::val_str(String* tmp)
 
6289
{
 
6290
  tmp=(*ref)->val_str(tmp);
 
6291
  null_value=(*ref)->null_value;
 
6292
  return tmp;
 
6293
}
 
6294
 
 
6295
 
 
6296
my_decimal *Item_direct_ref::val_decimal(my_decimal *decimal_value)
 
6297
{
 
6298
  my_decimal *tmp= (*ref)->val_decimal(decimal_value);
 
6299
  null_value=(*ref)->null_value;
 
6300
  return tmp;
 
6301
}
 
6302
 
 
6303
 
 
6304
bool Item_direct_ref::val_bool()
 
6305
{
 
6306
  bool tmp= (*ref)->val_bool();
 
6307
  null_value=(*ref)->null_value;
 
6308
  return tmp;
 
6309
}
 
6310
 
 
6311
 
 
6312
bool Item_direct_ref::is_null()
 
6313
{
 
6314
  return (*ref)->is_null();
 
6315
}
 
6316
 
 
6317
 
 
6318
bool Item_direct_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
 
6319
{
 
6320
  return (null_value=(*ref)->get_date(ltime,fuzzydate));
 
6321
}
 
6322
 
 
6323
 
 
6324
/**
 
6325
  Prepare referenced field then call usual Item_direct_ref::fix_fields .
 
6326
 
 
6327
  @param thd         thread handler
 
6328
  @param reference   reference on reference where this item stored
 
6329
 
 
6330
  @retval
 
6331
    FALSE   OK
 
6332
  @retval
 
6333
    TRUE    Error
 
6334
*/
 
6335
 
 
6336
bool Item_direct_view_ref::fix_fields(THD *thd, Item **reference)
 
6337
{
 
6338
  /* view fild reference must be defined */
 
6339
  DBUG_ASSERT(*ref);
 
6340
  /* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */
 
6341
  if ((*ref)->fixed)
 
6342
  {
 
6343
    Item *ref_item= (*ref)->real_item();
 
6344
    if (ref_item->type() == Item::FIELD_ITEM)
 
6345
    {
 
6346
      /*
 
6347
        In some cases we need to update table read set(see bug#47150).
 
6348
        If ref item is FIELD_ITEM and fixed then field and table
 
6349
        have proper values. So we can use them for update.
 
6350
      */
 
6351
      Field *fld= ((Item_field*) ref_item)->field;
 
6352
      DBUG_ASSERT(fld && fld->table);
 
6353
      if (thd->mark_used_columns == MARK_COLUMNS_READ)
 
6354
        bitmap_set_bit(fld->table->read_set, fld->field_index);
 
6355
    }
 
6356
  }
 
6357
  else if (!(*ref)->fixed &&
 
6358
           ((*ref)->fix_fields(thd, ref)))
 
6359
    return TRUE;
 
6360
 
 
6361
  return Item_direct_ref::fix_fields(thd, reference);
 
6362
}
 
6363
 
 
6364
/*
 
6365
  Prepare referenced outer field then call usual Item_direct_ref::fix_fields
 
6366
 
 
6367
  SYNOPSIS
 
6368
    Item_outer_ref::fix_fields()
 
6369
    thd         thread handler
 
6370
    reference   reference on reference where this item stored
 
6371
 
 
6372
  RETURN
 
6373
    FALSE   OK
 
6374
    TRUE    Error
 
6375
*/
 
6376
 
 
6377
bool Item_outer_ref::fix_fields(THD *thd, Item **reference)
 
6378
{
 
6379
  bool err;
 
6380
  /* outer_ref->check_cols() will be made in Item_direct_ref::fix_fields */
 
6381
  if ((*ref) && !(*ref)->fixed && ((*ref)->fix_fields(thd, reference)))
 
6382
    return TRUE;
 
6383
  err= Item_direct_ref::fix_fields(thd, reference);
 
6384
  if (!outer_ref)
 
6385
    outer_ref= *ref;
 
6386
  if ((*ref)->type() == Item::FIELD_ITEM)
 
6387
    table_name= ((Item_field*)outer_ref)->table_name;
 
6388
  return err;
 
6389
}
 
6390
 
 
6391
 
 
6392
/**
 
6393
  Compare two view column references for equality.
 
6394
 
 
6395
  A view column reference is considered equal to another column
 
6396
  reference if the second one is a view column and if both column
 
6397
  references resolve to the same item. It is assumed that both
 
6398
  items are of the same type.
 
6399
 
 
6400
  @param item        item to compare with
 
6401
  @param binary_cmp  make binary comparison
 
6402
 
 
6403
  @retval
 
6404
    TRUE    Referenced item is equal to given item
 
6405
  @retval
 
6406
    FALSE   otherwise
 
6407
*/
 
6408
 
 
6409
bool Item_direct_view_ref::eq(const Item *item, bool binary_cmp) const
 
6410
{
 
6411
  if (item->type() == REF_ITEM)
 
6412
  {
 
6413
    Item_ref *item_ref= (Item_ref*) item;
 
6414
    if (item_ref->ref_type() == VIEW_REF)
 
6415
    {
 
6416
      Item *item_ref_ref= *(item_ref->ref);
 
6417
      return ((*ref)->real_item() == item_ref_ref->real_item());
 
6418
    }
 
6419
  }
 
6420
  return FALSE;
 
6421
}
 
6422
 
 
6423
bool Item_default_value::eq(const Item *item, bool binary_cmp) const
 
6424
{
 
6425
  return item->type() == DEFAULT_VALUE_ITEM && 
 
6426
    ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
 
6427
}
 
6428
 
 
6429
 
 
6430
bool Item_default_value::fix_fields(THD *thd, Item **items)
 
6431
{
 
6432
  Item *real_arg;
 
6433
  Item_field *field_arg;
 
6434
  Field *def_field;
 
6435
  DBUG_ASSERT(fixed == 0);
 
6436
 
 
6437
  if (!arg)
 
6438
  {
 
6439
    fixed= 1;
 
6440
    return FALSE;
 
6441
  }
 
6442
  if (!arg->fixed && arg->fix_fields(thd, &arg))
 
6443
    goto error;
 
6444
 
 
6445
 
 
6446
  real_arg= arg->real_item();
 
6447
  if (real_arg->type() != FIELD_ITEM)
 
6448
  {
 
6449
    my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->name);
 
6450
    goto error;
 
6451
  }
 
6452
 
 
6453
  field_arg= (Item_field *)real_arg;
 
6454
  if (field_arg->field->flags & NO_DEFAULT_VALUE_FLAG)
 
6455
  {
 
6456
    my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), field_arg->field->field_name);
 
6457
    goto error;
 
6458
  }
 
6459
  if (!(def_field= (Field*) sql_alloc(field_arg->field->size_of())))
 
6460
    goto error;
 
6461
  memcpy(def_field, field_arg->field, field_arg->field->size_of());
 
6462
  def_field->move_field_offset((my_ptrdiff_t)
 
6463
                               (def_field->table->s->default_values -
 
6464
                                def_field->table->record[0]));
 
6465
  set_field(def_field);
 
6466
  return FALSE;
 
6467
 
 
6468
error:
 
6469
  context->process_error(thd);
 
6470
  return TRUE;
 
6471
}
 
6472
 
 
6473
 
 
6474
void Item_default_value::print(String *str, enum_query_type query_type)
 
6475
{
 
6476
  if (!arg)
 
6477
  {
 
6478
    str->append(STRING_WITH_LEN("default"));
 
6479
    return;
 
6480
  }
 
6481
  str->append(STRING_WITH_LEN("default("));
 
6482
  arg->print(str, query_type);
 
6483
  str->append(')');
 
6484
}
 
6485
 
 
6486
 
 
6487
int Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
 
6488
{
 
6489
  if (!arg)
 
6490
  {
 
6491
    if (field_arg->flags & NO_DEFAULT_VALUE_FLAG &&
 
6492
        field_arg->real_type() != MYSQL_TYPE_ENUM)
 
6493
    {
 
6494
      if (field_arg->reset())
 
6495
      {
 
6496
        my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
 
6497
                   ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
 
6498
        return -1;
 
6499
      }
 
6500
 
 
6501
      if (context->error_processor == &view_error_processor)
 
6502
      {
 
6503
        TABLE_LIST *view= cached_table->top_table();
 
6504
        push_warning_printf(field_arg->table->in_use,
 
6505
                            MYSQL_ERROR::WARN_LEVEL_WARN,
 
6506
                            ER_NO_DEFAULT_FOR_VIEW_FIELD,
 
6507
                            ER(ER_NO_DEFAULT_FOR_VIEW_FIELD),
 
6508
                            view->view_db.str,
 
6509
                            view->view_name.str);
 
6510
      }
 
6511
      else
 
6512
      {
 
6513
        push_warning_printf(field_arg->table->in_use,
 
6514
                            MYSQL_ERROR::WARN_LEVEL_WARN,
 
6515
                            ER_NO_DEFAULT_FOR_FIELD,
 
6516
                            ER(ER_NO_DEFAULT_FOR_FIELD),
 
6517
                            field_arg->field_name);
 
6518
      }
 
6519
      return 1;
 
6520
    }
 
6521
    field_arg->set_default();
 
6522
    return 0;
 
6523
  }
 
6524
  return Item_field::save_in_field(field_arg, no_conversions);
 
6525
}
 
6526
 
 
6527
 
 
6528
/**
 
6529
  This method like the walk method traverses the item tree, but at the
 
6530
  same time it can replace some nodes in the tree.
 
6531
*/ 
 
6532
 
 
6533
Item *Item_default_value::transform(Item_transformer transformer, uchar *args)
 
6534
{
 
6535
  DBUG_ASSERT(!current_thd->is_stmt_prepare());
 
6536
 
 
6537
  /*
 
6538
    If the value of arg is NULL, then this object represents a constant,
 
6539
    so further transformation is unnecessary (and impossible).
 
6540
  */
 
6541
  if (!arg)
 
6542
    return 0;
 
6543
 
 
6544
  Item *new_item= arg->transform(transformer, args);
 
6545
  if (!new_item)
 
6546
    return 0;
 
6547
 
 
6548
  /*
 
6549
    THD::change_item_tree() should be called only if the tree was
 
6550
    really transformed, i.e. when a new item has been created.
 
6551
    Otherwise we'll be allocating a lot of unnecessary memory for
 
6552
    change records at each execution.
 
6553
  */
 
6554
  if (arg != new_item)
 
6555
    current_thd->change_item_tree(&arg, new_item);
 
6556
  return (this->*transformer)(args);
 
6557
}
 
6558
 
 
6559
 
 
6560
bool Item_insert_value::eq(const Item *item, bool binary_cmp) const
 
6561
{
 
6562
  return item->type() == INSERT_VALUE_ITEM &&
 
6563
    ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
 
6564
}
 
6565
 
 
6566
 
 
6567
bool Item_insert_value::fix_fields(THD *thd, Item **items)
 
6568
{
 
6569
  DBUG_ASSERT(fixed == 0);
 
6570
  /* We should only check that arg is in first table */
 
6571
  if (!arg->fixed)
 
6572
  {
 
6573
    bool res;
 
6574
    TABLE_LIST *orig_next_table= context->last_name_resolution_table;
 
6575
    context->last_name_resolution_table= context->first_name_resolution_table;
 
6576
    res= arg->fix_fields(thd, &arg);
 
6577
    context->last_name_resolution_table= orig_next_table;
 
6578
    if (res)
 
6579
      return TRUE;
 
6580
  }
 
6581
 
 
6582
  if (arg->type() == REF_ITEM)
 
6583
  {
 
6584
    Item_ref *ref= (Item_ref *)arg;
 
6585
    if (ref->ref[0]->type() != FIELD_ITEM)
 
6586
    {
 
6587
      my_error(ER_BAD_FIELD_ERROR, MYF(0), "", "VALUES() function");
 
6588
      return TRUE;
 
6589
    }
 
6590
    arg= ref->ref[0];
 
6591
  }
 
6592
  /*
 
6593
    According to our SQL grammar, VALUES() function can reference
 
6594
    only to a column.
 
6595
  */
 
6596
  DBUG_ASSERT(arg->type() == FIELD_ITEM);
 
6597
 
 
6598
  Item_field *field_arg= (Item_field *)arg;
 
6599
 
 
6600
  if (field_arg->field->table->insert_values)
 
6601
  {
 
6602
    Field *def_field= (Field*) sql_alloc(field_arg->field->size_of());
 
6603
    if (!def_field)
 
6604
      return TRUE;
 
6605
    memcpy(def_field, field_arg->field, field_arg->field->size_of());
 
6606
    def_field->move_field_offset((my_ptrdiff_t)
 
6607
                                 (def_field->table->insert_values -
 
6608
                                  def_field->table->record[0]));
 
6609
    set_field(def_field);
 
6610
  }
 
6611
  else
 
6612
  {
 
6613
    Field *tmp_field= field_arg->field;
 
6614
    /* charset doesn't matter here, it's to avoid sigsegv only */
 
6615
    tmp_field= new Field_null(0, 0, Field::NONE, field_arg->field->field_name,
 
6616
                          &my_charset_bin);
 
6617
    if (tmp_field)
 
6618
    {
 
6619
      tmp_field->init(field_arg->field->table);
 
6620
      set_field(tmp_field);
 
6621
    }
 
6622
  }
 
6623
  return FALSE;
 
6624
}
 
6625
 
 
6626
void Item_insert_value::print(String *str, enum_query_type query_type)
 
6627
{
 
6628
  str->append(STRING_WITH_LEN("values("));
 
6629
  arg->print(str, query_type);
 
6630
  str->append(')');
 
6631
}
 
6632
 
 
6633
 
 
6634
/**
 
6635
  Find index of Field object which will be appropriate for item
 
6636
  representing field of row being changed in trigger.
 
6637
 
 
6638
  @param thd     current thread context
 
6639
  @param table   table of trigger (and where we looking for fields)
 
6640
  @param table_grant_info   GRANT_INFO of the subject table
 
6641
 
 
6642
  @note
 
6643
    This function does almost the same as fix_fields() for Item_field
 
6644
    but is invoked right after trigger definition parsing. Since at
 
6645
    this stage we can't say exactly what Field object (corresponding
 
6646
    to TABLE::record[0] or TABLE::record[1]) should be bound to this
 
6647
    Item, we only find out index of the Field and then select concrete
 
6648
    Field object in fix_fields() (by that time Table_trigger_list::old_field/
 
6649
    new_field should point to proper array of Fields).
 
6650
    It also binds Item_trigger_field to Table_triggers_list object for
 
6651
    table of trigger which uses this item.
 
6652
*/
 
6653
 
 
6654
void Item_trigger_field::setup_field(THD *thd, TABLE *table,
 
6655
                                     GRANT_INFO *table_grant_info)
 
6656
{
 
6657
  /*
 
6658
    It is too early to mark fields used here, because before execution
 
6659
    of statement that will invoke trigger other statements may use same
 
6660
    TABLE object, so all such mark-up will be wiped out.
 
6661
    So instead we do it in Table_triggers_list::mark_fields_used()
 
6662
    method which is called during execution of these statements.
 
6663
  */
 
6664
  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
 
6665
  thd->mark_used_columns= MARK_COLUMNS_NONE;
 
6666
  /*
 
6667
    Try to find field by its name and if it will be found
 
6668
    set field_idx properly.
 
6669
  */
 
6670
  (void)find_field_in_table(thd, table, field_name, (uint) strlen(field_name),
 
6671
                            0, &field_idx);
 
6672
  thd->mark_used_columns= save_mark_used_columns;
 
6673
  triggers= table->triggers;
 
6674
  table_grants= table_grant_info;
 
6675
}
 
6676
 
 
6677
 
 
6678
bool Item_trigger_field::eq(const Item *item, bool binary_cmp) const
 
6679
{
 
6680
  return item->type() == TRIGGER_FIELD_ITEM &&
 
6681
         row_version == ((Item_trigger_field *)item)->row_version &&
 
6682
         !my_strcasecmp(system_charset_info, field_name,
 
6683
                        ((Item_trigger_field *)item)->field_name);
 
6684
}
 
6685
 
 
6686
 
 
6687
void Item_trigger_field::set_required_privilege(bool rw)
 
6688
{
 
6689
  /*
 
6690
    Require SELECT and UPDATE privilege if this field will be read and
 
6691
    set, and only UPDATE privilege for setting the field.
 
6692
  */
 
6693
  want_privilege= (rw ? SELECT_ACL | UPDATE_ACL : UPDATE_ACL);
 
6694
}
 
6695
 
 
6696
 
 
6697
bool Item_trigger_field::set_value(THD *thd, sp_rcontext * /*ctx*/, Item **it)
 
6698
{
 
6699
  Item *item= sp_prepare_func_item(thd, it);
 
6700
 
 
6701
  return (!item || (!fixed && fix_fields(thd, 0)) ||
 
6702
          (item->save_in_field(field, 0) < 0));
 
6703
}
 
6704
 
 
6705
 
 
6706
bool Item_trigger_field::fix_fields(THD *thd, Item **items)
 
6707
{
 
6708
  /*
 
6709
    Since trigger is object tightly associated with TABLE object most
 
6710
    of its set up can be performed during trigger loading i.e. trigger
 
6711
    parsing! So we have little to do in fix_fields. :)
 
6712
  */
 
6713
 
 
6714
  DBUG_ASSERT(fixed == 0);
 
6715
 
 
6716
  /* Set field. */
 
6717
 
 
6718
  if (field_idx != (uint)-1)
 
6719
  {
 
6720
#ifndef NO_EMBEDDED_ACCESS_CHECKS
 
6721
    /*
 
6722
      Check access privileges for the subject table. We check privileges only
 
6723
      in runtime.
 
6724
    */
 
6725
 
 
6726
    if (table_grants)
 
6727
    {
 
6728
      table_grants->want_privilege= want_privilege;
 
6729
 
 
6730
      if (check_grant_column(thd, table_grants, triggers->trigger_table->s->db.str,
 
6731
                             triggers->trigger_table->s->table_name.str, field_name,
 
6732
                             strlen(field_name), thd->security_ctx))
 
6733
        return TRUE;
 
6734
    }
 
6735
#endif // NO_EMBEDDED_ACCESS_CHECKS
 
6736
 
 
6737
    field= (row_version == OLD_ROW) ? triggers->old_field[field_idx] :
 
6738
                                      triggers->new_field[field_idx];
 
6739
    set_field(field);
 
6740
    fixed= 1;
 
6741
    return FALSE;
 
6742
  }
 
6743
 
 
6744
  my_error(ER_BAD_FIELD_ERROR, MYF(0), field_name,
 
6745
           (row_version == NEW_ROW) ? "NEW" : "OLD");
 
6746
  return TRUE;
 
6747
}
 
6748
 
 
6749
 
 
6750
void Item_trigger_field::print(String *str, enum_query_type query_type)
 
6751
{
 
6752
  str->append((row_version == NEW_ROW) ? "NEW" : "OLD", 3);
 
6753
  str->append('.');
 
6754
  str->append(field_name);
 
6755
}
 
6756
 
 
6757
 
 
6758
void Item_trigger_field::cleanup()
 
6759
{
 
6760
  want_privilege= original_privilege;
 
6761
  /*
 
6762
    Since special nature of Item_trigger_field we should not do most of
 
6763
    things from Item_field::cleanup() or Item_ident::cleanup() here.
 
6764
  */
 
6765
  Item::cleanup();
 
6766
}
 
6767
 
 
6768
 
 
6769
Item_result item_cmp_type(Item_result a,Item_result b)
 
6770
{
 
6771
  if (a == STRING_RESULT && b == STRING_RESULT)
 
6772
    return STRING_RESULT;
 
6773
  if (a == INT_RESULT && b == INT_RESULT)
 
6774
    return INT_RESULT;
 
6775
  else if (a == ROW_RESULT || b == ROW_RESULT)
 
6776
    return ROW_RESULT;
 
6777
  if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
 
6778
      (b == INT_RESULT || b == DECIMAL_RESULT))
 
6779
    return DECIMAL_RESULT;
 
6780
  return REAL_RESULT;
 
6781
}
 
6782
 
 
6783
 
 
6784
void resolve_const_item(THD *thd, Item **ref, Item *comp_item)
 
6785
{
 
6786
  Item *item= *ref;
 
6787
  Item *new_item= NULL;
 
6788
  if (item->basic_const_item())
 
6789
    return;                                     // Can't be better
 
6790
  Item_result res_type=item_cmp_type(comp_item->result_type(),
 
6791
                                     item->result_type());
 
6792
  char *name=item->name;                        // Alloced by sql_alloc
 
6793
 
 
6794
  switch (res_type) {
 
6795
  case STRING_RESULT:
 
6796
  {
 
6797
    char buff[MAX_FIELD_WIDTH];
 
6798
    String tmp(buff,sizeof(buff),&my_charset_bin),*result;
 
6799
    result=item->val_str(&tmp);
 
6800
    if (item->null_value)
 
6801
      new_item= new Item_null(name);
 
6802
    else
 
6803
    {
 
6804
      uint length= result->length();
 
6805
      char *tmp_str= sql_strmake(result->ptr(), length);
 
6806
      new_item= new Item_string(name, tmp_str, length, result->charset());
 
6807
    }
 
6808
    break;
 
6809
  }
 
6810
  case INT_RESULT:
 
6811
  {
 
6812
    longlong result=item->val_int();
 
6813
    uint length=item->max_length;
 
6814
    bool null_value=item->null_value;
 
6815
    new_item= (null_value ? (Item*) new Item_null(name) :
 
6816
               (Item*) new Item_int(name, result, length));
 
6817
    break;
 
6818
  }
 
6819
  case ROW_RESULT:
 
6820
  if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
 
6821
  {
 
6822
    /*
 
6823
      Substitute constants only in Item_rows. Don't affect other Items
 
6824
      with ROW_RESULT (eg Item_singlerow_subselect).
 
6825
 
 
6826
      For such Items more optimal is to detect if it is constant and replace
 
6827
      it with Item_row. This would optimize queries like this:
 
6828
      SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
 
6829
    */
 
6830
    Item_row *item_row= (Item_row*) item;
 
6831
    Item_row *comp_item_row= (Item_row*) comp_item;
 
6832
    uint col;
 
6833
    new_item= 0;
 
6834
    /*
 
6835
      If item and comp_item are both Item_rows and have same number of cols
 
6836
      then process items in Item_row one by one.
 
6837
      We can't ignore NULL values here as this item may be used with <=>, in
 
6838
      which case NULL's are significant.
 
6839
    */
 
6840
    DBUG_ASSERT(item->result_type() == comp_item->result_type());
 
6841
    DBUG_ASSERT(item_row->cols() == comp_item_row->cols());
 
6842
    col= item_row->cols();
 
6843
    while (col-- > 0)
 
6844
      resolve_const_item(thd, item_row->addr(col),
 
6845
                         comp_item_row->element_index(col));
 
6846
    break;
 
6847
  }
 
6848
  /* Fallthrough */
 
6849
  case REAL_RESULT:
 
6850
  {                                             // It must REAL_RESULT
 
6851
    double result= item->val_real();
 
6852
    uint length=item->max_length,decimals=item->decimals;
 
6853
    bool null_value=item->null_value;
 
6854
    new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
 
6855
               new Item_float(name, result, decimals, length));
 
6856
    break;
 
6857
  }
 
6858
  case DECIMAL_RESULT:
 
6859
  {
 
6860
    my_decimal decimal_value;
 
6861
    my_decimal *result= item->val_decimal(&decimal_value);
 
6862
    uint length= item->max_length, decimals= item->decimals;
 
6863
    bool null_value= item->null_value;
 
6864
    new_item= (null_value ?
 
6865
               (Item*) new Item_null(name) :
 
6866
               (Item*) new Item_decimal(name, result, length, decimals));
 
6867
    break;
 
6868
  }
 
6869
  default:
 
6870
    DBUG_ASSERT(0);
 
6871
  }
 
6872
  if (new_item)
 
6873
    thd->change_item_tree(ref, new_item);
 
6874
}
 
6875
 
 
6876
/**
 
6877
  Compare the value stored in field with the expression from the query.
 
6878
 
 
6879
  @param field   Field which the Item is stored in after conversion
 
6880
  @param item    Original expression from query
 
6881
 
 
6882
  @return Returns an integer greater than, equal to, or less than 0 if
 
6883
          the value stored in the field is greater than, equal to,
 
6884
          or less than the original Item. A 0 may also be returned if 
 
6885
          out of memory.          
 
6886
 
 
6887
  @note We only use this on the range optimizer/partition pruning,
 
6888
        because in some cases we can't store the value in the field
 
6889
        without some precision/character loss.
 
6890
*/
 
6891
 
 
6892
int stored_field_cmp_to_item(THD *thd, Field *field, Item *item)
 
6893
{
 
6894
  Item_result res_type=item_cmp_type(field->result_type(),
 
6895
                                     item->result_type());
 
6896
  if (res_type == STRING_RESULT)
 
6897
  {
 
6898
    char item_buff[MAX_FIELD_WIDTH];
 
6899
    char field_buff[MAX_FIELD_WIDTH];
 
6900
    
 
6901
    String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin);
 
6902
    String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
 
6903
    String *item_result= item->val_str(&item_tmp);
 
6904
    /*
 
6905
      Some implementations of Item::val_str(String*) actually modify
 
6906
      the field Item::null_value, hence we can't check it earlier.
 
6907
    */
 
6908
    if (item->null_value)
 
6909
      return 0;
 
6910
    String *field_result= field->val_str(&field_tmp);
 
6911
 
 
6912
    enum_field_types field_type= field->type();
 
6913
 
 
6914
    if (field_type == MYSQL_TYPE_DATE || field_type == MYSQL_TYPE_DATETIME)
 
6915
    {
 
6916
      enum_mysql_timestamp_type type= MYSQL_TIMESTAMP_ERROR;
 
6917
 
 
6918
      if (field_type == MYSQL_TYPE_DATE)
 
6919
        type= MYSQL_TIMESTAMP_DATE;
 
6920
 
 
6921
      if (field_type == MYSQL_TYPE_DATETIME)
 
6922
        type= MYSQL_TIMESTAMP_DATETIME;
 
6923
        
 
6924
      const char *field_name= field->field_name;
 
6925
      MYSQL_TIME field_time, item_time;
 
6926
      get_mysql_time_from_str(thd, field_result, type, field_name, &field_time);
 
6927
      get_mysql_time_from_str(thd, item_result, type, field_name,  &item_time);
 
6928
 
 
6929
      return my_time_compare(&field_time, &item_time);
 
6930
    }
 
6931
    return stringcmp(field_result, item_result);
 
6932
  }
 
6933
  if (res_type == INT_RESULT)
 
6934
    return 0;                                   // Both are of type int
 
6935
  if (res_type == DECIMAL_RESULT)
 
6936
  {
 
6937
    my_decimal item_buf, *item_val,
 
6938
               field_buf, *field_val;
 
6939
    item_val= item->val_decimal(&item_buf);
 
6940
    if (item->null_value)
 
6941
      return 0;
 
6942
    field_val= field->val_decimal(&field_buf);
 
6943
    return my_decimal_cmp(item_val, field_val);
 
6944
  }
 
6945
  double result= item->val_real();
 
6946
  if (item->null_value)
 
6947
    return 0;
 
6948
  double field_result= field->val_real();
 
6949
  if (field_result < result)
 
6950
    return -1;
 
6951
  else if (field_result > result)
 
6952
    return 1;
 
6953
  return 0;
 
6954
}
 
6955
 
 
6956
Item_cache* Item_cache::get_cache(const Item *item)
 
6957
{
 
6958
  return get_cache(item, item->result_type());
 
6959
}
 
6960
 
 
6961
 
 
6962
/**
 
6963
  Get a cache item of given type.
 
6964
 
 
6965
  @param item         value to be cached
 
6966
  @param type         required type of cache
 
6967
 
 
6968
  @return cache item
 
6969
*/
 
6970
 
 
6971
Item_cache* Item_cache::get_cache(const Item *item, const Item_result type)
 
6972
{
 
6973
  switch (type) {
 
6974
  case INT_RESULT:
 
6975
    return new Item_cache_int(item->field_type());
 
6976
  case REAL_RESULT:
 
6977
    return new Item_cache_real();
 
6978
  case DECIMAL_RESULT:
 
6979
    return new Item_cache_decimal();
 
6980
  case STRING_RESULT:
 
6981
    return new Item_cache_str(item);
 
6982
  case ROW_RESULT:
 
6983
    return new Item_cache_row();
 
6984
  default:
 
6985
    // should never be in real life
 
6986
    DBUG_ASSERT(0);
 
6987
    return 0;
 
6988
  }
 
6989
}
 
6990
 
 
6991
void Item_cache::store(Item *item)
 
6992
{
 
6993
  example= item;
 
6994
  if (!item)
 
6995
    null_value= TRUE;
 
6996
  value_cached= FALSE;
 
6997
}
 
6998
 
 
6999
void Item_cache::print(String *str, enum_query_type query_type)
 
7000
{
 
7001
  str->append(STRING_WITH_LEN("<cache>("));
 
7002
  if (example)
 
7003
    example->print(str, query_type);
 
7004
  else
 
7005
    Item::print(str, query_type);
 
7006
  str->append(')');
 
7007
}
 
7008
 
 
7009
bool  Item_cache_int::cache_value()
 
7010
{
 
7011
  if (!example)
 
7012
    return FALSE;
 
7013
  value_cached= TRUE;
 
7014
  value= example->val_int_result();
 
7015
  null_value= example->null_value;
 
7016
  unsigned_flag= example->unsigned_flag;
 
7017
  return TRUE;
 
7018
}
 
7019
 
 
7020
 
 
7021
void Item_cache_int::store(Item *item, longlong val_arg)
 
7022
{
 
7023
  /* An explicit values is given, save it. */
 
7024
  value_cached= TRUE;
 
7025
  value= val_arg;
 
7026
  null_value= item->null_value;
 
7027
  unsigned_flag= item->unsigned_flag;
 
7028
}
 
7029
 
 
7030
 
 
7031
String *Item_cache_int::val_str(String *str)
 
7032
{
 
7033
  DBUG_ASSERT(fixed == 1);
 
7034
  if (!value_cached && !cache_value())
 
7035
    return NULL;
 
7036
  str->set(value, default_charset());
 
7037
  return str;
 
7038
}
 
7039
 
 
7040
 
 
7041
my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val)
 
7042
{
 
7043
  DBUG_ASSERT(fixed == 1);
 
7044
  if (!value_cached && !cache_value())
 
7045
    return NULL;
 
7046
  int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val);
 
7047
  return decimal_val;
 
7048
}
 
7049
 
 
7050
double Item_cache_int::val_real()
 
7051
{
 
7052
  DBUG_ASSERT(fixed == 1);
 
7053
  if (!value_cached && !cache_value())
 
7054
    return 0.0;
 
7055
  return (double) value;
 
7056
}
 
7057
 
 
7058
longlong Item_cache_int::val_int()
 
7059
{
 
7060
  DBUG_ASSERT(fixed == 1);
 
7061
  if (!value_cached && !cache_value())
 
7062
    return 0;
 
7063
  return value;
 
7064
}
 
7065
 
 
7066
bool Item_cache_real::cache_value()
 
7067
{
 
7068
  if (!example)
 
7069
    return FALSE;
 
7070
  value_cached= TRUE;
 
7071
  value= example->val_result();
 
7072
  null_value= example->null_value;
 
7073
  return TRUE;
 
7074
}
 
7075
 
 
7076
 
 
7077
double Item_cache_real::val_real()
 
7078
{
 
7079
  DBUG_ASSERT(fixed == 1);
 
7080
  if (!value_cached && !cache_value())
 
7081
    return 0.0;
 
7082
  return value;
 
7083
}
 
7084
 
 
7085
longlong Item_cache_real::val_int()
 
7086
{
 
7087
  DBUG_ASSERT(fixed == 1);
 
7088
  if (!value_cached && !cache_value())
 
7089
    return 0;
 
7090
  return (longlong) rint(value);
 
7091
}
 
7092
 
 
7093
 
 
7094
String* Item_cache_real::val_str(String *str)
 
7095
{
 
7096
  DBUG_ASSERT(fixed == 1);
 
7097
  if (!value_cached && !cache_value())
 
7098
    return NULL;
 
7099
  str->set_real(value, decimals, default_charset());
 
7100
  return str;
 
7101
}
 
7102
 
 
7103
 
 
7104
my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val)
 
7105
{
 
7106
  DBUG_ASSERT(fixed == 1);
 
7107
  if (!value_cached && !cache_value())
 
7108
    return NULL;
 
7109
  double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
 
7110
  return decimal_val;
 
7111
}
 
7112
 
 
7113
 
 
7114
bool Item_cache_decimal::cache_value()
 
7115
{
 
7116
  if (!example)
 
7117
    return FALSE;
 
7118
  value_cached= TRUE;
 
7119
  my_decimal *val= example->val_decimal_result(&decimal_value);
 
7120
  if (!(null_value= example->null_value) && val != &decimal_value)
 
7121
    my_decimal2decimal(val, &decimal_value);
 
7122
  return TRUE;
 
7123
}
 
7124
 
 
7125
double Item_cache_decimal::val_real()
 
7126
{
 
7127
  DBUG_ASSERT(fixed);
 
7128
  double res;
 
7129
  if (!value_cached && !cache_value())
 
7130
    return NULL;
 
7131
  my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res);
 
7132
  return res;
 
7133
}
 
7134
 
 
7135
longlong Item_cache_decimal::val_int()
 
7136
{
 
7137
  DBUG_ASSERT(fixed);
 
7138
  longlong res;
 
7139
  if (!value_cached && !cache_value())
 
7140
    return 0;
 
7141
  my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res);
 
7142
  return res;
 
7143
}
 
7144
 
 
7145
String* Item_cache_decimal::val_str(String *str)
 
7146
{
 
7147
  DBUG_ASSERT(fixed);
 
7148
  if (!value_cached && !cache_value())
 
7149
    return NULL;
 
7150
  my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, FALSE,
 
7151
                   &decimal_value);
 
7152
  my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str);
 
7153
  return str;
 
7154
}
 
7155
 
 
7156
my_decimal *Item_cache_decimal::val_decimal(my_decimal *val)
 
7157
{
 
7158
  DBUG_ASSERT(fixed);
 
7159
  if (!value_cached && !cache_value())
 
7160
    return NULL;
 
7161
  return &decimal_value;
 
7162
}
 
7163
 
 
7164
 
 
7165
bool Item_cache_str::cache_value()
 
7166
{
 
7167
  if (!example)
 
7168
    return FALSE;
 
7169
  value_cached= TRUE;
 
7170
  value_buff.set(buffer, sizeof(buffer), example->collation.collation);
 
7171
  value= example->str_result(&value_buff);
 
7172
  if ((null_value= example->null_value))
 
7173
    value= 0;
 
7174
  else if (value != &value_buff)
 
7175
  {
 
7176
    /*
 
7177
      We copy string value to avoid changing value if 'item' is table field
 
7178
      in queries like following (where t1.c is varchar):
 
7179
      select a, 
 
7180
             (select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'),
 
7181
             (select c from t1 where a=t2.a)
 
7182
        from t2;
 
7183
    */
 
7184
    value_buff.copy(*value);
 
7185
    value= &value_buff;
 
7186
  }
 
7187
  return TRUE;
 
7188
}
 
7189
 
 
7190
double Item_cache_str::val_real()
 
7191
{
 
7192
  DBUG_ASSERT(fixed == 1);
 
7193
  int err_not_used;
 
7194
  char *end_not_used;
 
7195
  if (!value_cached && !cache_value())
 
7196
    return 0.0;
 
7197
  if (value)
 
7198
    return my_strntod(value->charset(), (char*) value->ptr(),
 
7199
                      value->length(), &end_not_used, &err_not_used);
 
7200
  return (double) 0;
 
7201
}
 
7202
 
 
7203
 
 
7204
longlong Item_cache_str::val_int()
 
7205
{
 
7206
  DBUG_ASSERT(fixed == 1);
 
7207
  int err;
 
7208
  if (!value_cached && !cache_value())
 
7209
    return 0;
 
7210
  if (value)
 
7211
    return my_strntoll(value->charset(), value->ptr(),
 
7212
                       value->length(), 10, (char**) 0, &err);
 
7213
  else
 
7214
    return (longlong)0;
 
7215
}
 
7216
 
 
7217
 
 
7218
String* Item_cache_str::val_str(String *str)
 
7219
{
 
7220
  DBUG_ASSERT(fixed == 1);
 
7221
  if (!value_cached && !cache_value())
 
7222
    return 0;
 
7223
  return value;
 
7224
}
 
7225
 
 
7226
 
 
7227
my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val)
 
7228
{
 
7229
  DBUG_ASSERT(fixed == 1);
 
7230
  if (!value_cached && !cache_value())
 
7231
    return NULL;
 
7232
  if (value)
 
7233
    string2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
 
7234
  else
 
7235
    decimal_val= 0;
 
7236
  return decimal_val;
 
7237
}
 
7238
 
 
7239
 
 
7240
int Item_cache_str::save_in_field(Field *field, bool no_conversions)
 
7241
{
 
7242
  if (!value_cached && !cache_value())
 
7243
    return 0;
 
7244
  int res= Item_cache::save_in_field(field, no_conversions);
 
7245
  return (is_varbinary && field->type() == MYSQL_TYPE_STRING &&
 
7246
          value->length() < field->field_length) ? 1 : res;
 
7247
}
 
7248
 
 
7249
 
 
7250
bool Item_cache_row::allocate(uint num)
 
7251
{
 
7252
  item_count= num;
 
7253
  THD *thd= current_thd;
 
7254
  return (!(values= 
 
7255
            (Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
 
7256
}
 
7257
 
 
7258
 
 
7259
bool Item_cache_row::setup(Item * item)
 
7260
{
 
7261
  example= item;
 
7262
  if (!values && allocate(item->cols()))
 
7263
    return 1;
 
7264
  for (uint i= 0; i < item_count; i++)
 
7265
  {
 
7266
    Item *el= item->element_index(i);
 
7267
    Item_cache *tmp;
 
7268
    if (!(tmp= values[i]= Item_cache::get_cache(el)))
 
7269
      return 1;
 
7270
    tmp->setup(el);
 
7271
  }
 
7272
  return 0;
 
7273
}
 
7274
 
 
7275
 
 
7276
void Item_cache_row::store(Item * item)
 
7277
{
 
7278
  example= item;
 
7279
  if (!item)
 
7280
  {
 
7281
    null_value= TRUE;
 
7282
    return;
 
7283
  }
 
7284
  for (uint i= 0; i < item_count; i++)
 
7285
    values[i]->store(item->element_index(i));
 
7286
}
 
7287
 
 
7288
 
 
7289
bool Item_cache_row::cache_value()
 
7290
{
 
7291
  if (!example)
 
7292
    return FALSE;
 
7293
  value_cached= TRUE;
 
7294
  null_value= 0;
 
7295
  example->bring_value();
 
7296
  for (uint i= 0; i < item_count; i++)
 
7297
  {
 
7298
    values[i]->cache_value();
 
7299
    null_value|= values[i]->null_value;
 
7300
  }
 
7301
  return TRUE;
 
7302
}
 
7303
 
 
7304
 
 
7305
void Item_cache_row::illegal_method_call(const char *method)
 
7306
{
 
7307
  DBUG_ENTER("Item_cache_row::illegal_method_call");
 
7308
  DBUG_PRINT("error", ("!!! %s method was called for row item", method));
 
7309
  DBUG_ASSERT(0);
 
7310
  my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
 
7311
  DBUG_VOID_RETURN;
 
7312
}
 
7313
 
 
7314
 
 
7315
bool Item_cache_row::check_cols(uint c)
 
7316
{
 
7317
  if (c != item_count)
 
7318
  {
 
7319
    my_error(ER_OPERAND_COLUMNS, MYF(0), c);
 
7320
    return 1;
 
7321
  }
 
7322
  return 0;
 
7323
}
 
7324
 
 
7325
 
 
7326
bool Item_cache_row::null_inside()
 
7327
{
 
7328
  for (uint i= 0; i < item_count; i++)
 
7329
  {
 
7330
    if (values[i]->cols() > 1)
 
7331
    {
 
7332
      if (values[i]->null_inside())
 
7333
        return 1;
 
7334
    }
 
7335
    else
 
7336
    {
 
7337
      values[i]->update_null_value();
 
7338
      if (values[i]->null_value)
 
7339
        return 1;
 
7340
    }
 
7341
  }
 
7342
  return 0;
 
7343
}
 
7344
 
 
7345
 
 
7346
void Item_cache_row::bring_value()
 
7347
{
 
7348
  for (uint i= 0; i < item_count; i++)
 
7349
    values[i]->bring_value();
 
7350
  return;
 
7351
}
 
7352
 
 
7353
 
 
7354
Item_type_holder::Item_type_holder(THD *thd, Item *item)
 
7355
  :Item(thd, item), enum_set_typelib(0), fld_type(get_real_type(item))
 
7356
{
 
7357
  DBUG_ASSERT(item->fixed);
 
7358
  maybe_null= item->maybe_null;
 
7359
  collation.set(item->collation);
 
7360
  get_full_info(item);
 
7361
  /* fix variable decimals which always is NOT_FIXED_DEC */
 
7362
  if (Field::result_merge_type(fld_type) == INT_RESULT)
 
7363
    decimals= 0;
 
7364
  prev_decimal_int_part= item->decimal_int_part();
 
7365
#ifdef HAVE_SPATIAL
 
7366
  if (item->field_type() == MYSQL_TYPE_GEOMETRY)
 
7367
    geometry_type= item->get_geometry_type();
 
7368
#endif /* HAVE_SPATIAL */
 
7369
}
 
7370
 
 
7371
 
 
7372
/**
 
7373
  Return expression type of Item_type_holder.
 
7374
 
 
7375
  @return
 
7376
    Item_result (type of internal MySQL expression result)
 
7377
*/
 
7378
 
 
7379
Item_result Item_type_holder::result_type() const
 
7380
{
 
7381
  return Field::result_merge_type(fld_type);
 
7382
}
 
7383
 
 
7384
 
 
7385
/**
 
7386
  Find real field type of item.
 
7387
 
 
7388
  @return
 
7389
    type of field which should be created to store item value
 
7390
*/
 
7391
 
 
7392
enum_field_types Item_type_holder::get_real_type(Item *item)
 
7393
{
 
7394
  switch(item->type())
 
7395
  {
 
7396
  case FIELD_ITEM:
 
7397
  {
 
7398
    /*
 
7399
      Item_fields::field_type ask Field_type() but sometimes field return
 
7400
      a different type, like for enum/set, so we need to ask real type.
 
7401
    */
 
7402
    Field *field= ((Item_field *) item)->field;
 
7403
    enum_field_types type= field->real_type();
 
7404
    if (field->is_created_from_null_item)
 
7405
      return MYSQL_TYPE_NULL;
 
7406
    /* work around about varchar type field detection */
 
7407
    if (type == MYSQL_TYPE_STRING && field->type() == MYSQL_TYPE_VAR_STRING)
 
7408
      return MYSQL_TYPE_VAR_STRING;
 
7409
    return type;
 
7410
  }
 
7411
  case SUM_FUNC_ITEM:
 
7412
  {
 
7413
    /*
 
7414
      Argument of aggregate function sometimes should be asked about field
 
7415
      type
 
7416
    */
 
7417
    Item_sum *item_sum= (Item_sum *) item;
 
7418
    if (item_sum->keep_field_type())
 
7419
      return get_real_type(item_sum->get_arg(0));
 
7420
    break;
 
7421
  }
 
7422
  case FUNC_ITEM:
 
7423
    if (((Item_func *) item)->functype() == Item_func::GUSERVAR_FUNC)
 
7424
    {
 
7425
      /*
 
7426
        There are work around of problem with changing variable type on the
 
7427
        fly and variable always report "string" as field type to get
 
7428
        acceptable information for client in send_field, so we make field
 
7429
        type from expression type.
 
7430
      */
 
7431
      switch (item->result_type()) {
 
7432
      case STRING_RESULT:
 
7433
        return MYSQL_TYPE_VAR_STRING;
 
7434
      case INT_RESULT:
 
7435
        return MYSQL_TYPE_LONGLONG;
 
7436
      case REAL_RESULT:
 
7437
        return MYSQL_TYPE_DOUBLE;
 
7438
      case DECIMAL_RESULT:
 
7439
        return MYSQL_TYPE_NEWDECIMAL;
 
7440
      case ROW_RESULT:
 
7441
      default:
 
7442
        DBUG_ASSERT(0);
 
7443
        return MYSQL_TYPE_VAR_STRING;
 
7444
      }
 
7445
    }
 
7446
    break;
 
7447
  default:
 
7448
    break;
 
7449
  }
 
7450
  return item->field_type();
 
7451
}
 
7452
 
 
7453
/**
 
7454
  Find field type which can carry current Item_type_holder type and
 
7455
  type of given Item.
 
7456
 
 
7457
  @param thd     thread handler
 
7458
  @param item    given item to join its parameters with this item ones
 
7459
 
 
7460
  @retval
 
7461
    TRUE   error - types are incompatible
 
7462
  @retval
 
7463
    FALSE  OK
 
7464
*/
 
7465
 
 
7466
bool Item_type_holder::join_types(THD *thd, Item *item)
 
7467
{
 
7468
  uint max_length_orig= max_length;
 
7469
  uint decimals_orig= decimals;
 
7470
  DBUG_ENTER("Item_type_holder::join_types");
 
7471
  DBUG_PRINT("info:", ("was type %d len %d, dec %d name %s",
 
7472
                       fld_type, max_length, decimals,
 
7473
                       (name ? name : "<NULL>")));
 
7474
  DBUG_PRINT("info:", ("in type %d len %d, dec %d",
 
7475
                       get_real_type(item),
 
7476
                       item->max_length, item->decimals));
 
7477
  fld_type= Field::field_type_merge(fld_type, get_real_type(item));
 
7478
  {
 
7479
    int item_decimals= item->decimals;
 
7480
    /* fix variable decimals which always is NOT_FIXED_DEC */
 
7481
    if (Field::result_merge_type(fld_type) == INT_RESULT)
 
7482
      item_decimals= 0;
 
7483
    decimals= max(decimals, item_decimals);
 
7484
  }
 
7485
  if (Field::result_merge_type(fld_type) == DECIMAL_RESULT)
 
7486
  {
 
7487
    decimals= min(max(decimals, item->decimals), DECIMAL_MAX_SCALE);
 
7488
    int item_int_part= item->decimal_int_part();
 
7489
    int item_prec = max(prev_decimal_int_part, item_int_part) + decimals;
 
7490
    int precision= min(item_prec, DECIMAL_MAX_PRECISION);
 
7491
    unsigned_flag&= item->unsigned_flag;
 
7492
    max_length= my_decimal_precision_to_length_no_truncation(precision,
 
7493
                                                             decimals,
 
7494
                                                             unsigned_flag);
 
7495
  }
 
7496
 
 
7497
  switch (Field::result_merge_type(fld_type))
 
7498
  {
 
7499
  case STRING_RESULT:
 
7500
  {
 
7501
    const char *old_cs, *old_derivation;
 
7502
    uint32 old_max_chars= max_length / collation.collation->mbmaxlen;
 
7503
    old_cs= collation.collation->name;
 
7504
    old_derivation= collation.derivation_name();
 
7505
    if (collation.aggregate(item->collation, MY_COLL_ALLOW_CONV))
 
7506
    {
 
7507
      my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
 
7508
               old_cs, old_derivation,
 
7509
               item->collation.collation->name,
 
7510
               item->collation.derivation_name(),
 
7511
               "UNION");
 
7512
      DBUG_RETURN(TRUE);
 
7513
    }
 
7514
    /*
 
7515
      To figure out max_length, we have to take into account possible
 
7516
      expansion of the size of the values because of character set
 
7517
      conversions.
 
7518
     */
 
7519
    if (collation.collation != &my_charset_bin)
 
7520
    {
 
7521
      max_length= max(old_max_chars * collation.collation->mbmaxlen,
 
7522
                      display_length(item) /
 
7523
                      item->collation.collation->mbmaxlen *
 
7524
                      collation.collation->mbmaxlen);
 
7525
    }
 
7526
    else
 
7527
      set_if_bigger(max_length, display_length(item));
 
7528
    break;
 
7529
  }
 
7530
  case REAL_RESULT:
 
7531
  {
 
7532
    if (decimals != NOT_FIXED_DEC)
 
7533
    {
 
7534
      /*
 
7535
        For FLOAT(M,D)/DOUBLE(M,D) do not change precision
 
7536
         if both fields have the same M and D
 
7537
      */
 
7538
      if (item->max_length != max_length_orig ||
 
7539
          item->decimals != decimals_orig)
 
7540
      {
 
7541
        int delta1= max_length_orig - decimals_orig;
 
7542
        int delta2= item->max_length - item->decimals;
 
7543
        max_length= max(delta1, delta2) + decimals;
 
7544
        if (fld_type == MYSQL_TYPE_FLOAT && max_length > FLT_DIG + 2)
 
7545
        {
 
7546
          max_length= MAX_FLOAT_STR_LENGTH;
 
7547
          decimals= NOT_FIXED_DEC;
 
7548
        } 
 
7549
        else if (fld_type == MYSQL_TYPE_DOUBLE && max_length > DBL_DIG + 2)
 
7550
        {
 
7551
          max_length= MAX_DOUBLE_STR_LENGTH;
 
7552
          decimals= NOT_FIXED_DEC;
 
7553
        }
 
7554
      }
 
7555
    }
 
7556
    else
 
7557
      max_length= (fld_type == MYSQL_TYPE_FLOAT) ? FLT_DIG+6 : DBL_DIG+7;
 
7558
    break;
 
7559
  }
 
7560
  default:
 
7561
    max_length= max(max_length, display_length(item));
 
7562
  };
 
7563
  maybe_null|= item->maybe_null;
 
7564
  get_full_info(item);
 
7565
 
 
7566
  /* Remember decimal integer part to be used in DECIMAL_RESULT handleng */
 
7567
  prev_decimal_int_part= decimal_int_part();
 
7568
  DBUG_PRINT("info", ("become type: %d  len: %u  dec: %u",
 
7569
                      (int) fld_type, max_length, (uint) decimals));
 
7570
  DBUG_RETURN(FALSE);
 
7571
}
 
7572
 
 
7573
/**
 
7574
  Calculate lenth for merging result for given Item type.
 
7575
 
 
7576
  @param item  Item for length detection
 
7577
 
 
7578
  @return
 
7579
    length
 
7580
*/
 
7581
 
 
7582
uint32 Item_type_holder::display_length(Item *item)
 
7583
{
 
7584
  if (item->type() == Item::FIELD_ITEM)
 
7585
    return ((Item_field *)item)->max_disp_length();
 
7586
 
 
7587
  switch (item->field_type())
 
7588
  {
 
7589
  case MYSQL_TYPE_DECIMAL:
 
7590
  case MYSQL_TYPE_TIMESTAMP:
 
7591
  case MYSQL_TYPE_DATE:
 
7592
  case MYSQL_TYPE_TIME:
 
7593
  case MYSQL_TYPE_DATETIME:
 
7594
  case MYSQL_TYPE_YEAR:
 
7595
  case MYSQL_TYPE_NEWDATE:
 
7596
  case MYSQL_TYPE_VARCHAR:
 
7597
  case MYSQL_TYPE_BIT:
 
7598
  case MYSQL_TYPE_NEWDECIMAL:
 
7599
  case MYSQL_TYPE_ENUM:
 
7600
  case MYSQL_TYPE_SET:
 
7601
  case MYSQL_TYPE_TINY_BLOB:
 
7602
  case MYSQL_TYPE_MEDIUM_BLOB:
 
7603
  case MYSQL_TYPE_LONG_BLOB:
 
7604
  case MYSQL_TYPE_BLOB:
 
7605
  case MYSQL_TYPE_VAR_STRING:
 
7606
  case MYSQL_TYPE_STRING:
 
7607
  case MYSQL_TYPE_GEOMETRY:
 
7608
    return item->max_length;
 
7609
  case MYSQL_TYPE_TINY:
 
7610
    return 4;
 
7611
  case MYSQL_TYPE_SHORT:
 
7612
    return 6;
 
7613
  case MYSQL_TYPE_LONG:
 
7614
    return MY_INT32_NUM_DECIMAL_DIGITS;
 
7615
  case MYSQL_TYPE_FLOAT:
 
7616
    return 25;
 
7617
  case MYSQL_TYPE_DOUBLE:
 
7618
    return 53;
 
7619
  case MYSQL_TYPE_NULL:
 
7620
    return 0;
 
7621
  case MYSQL_TYPE_LONGLONG:
 
7622
    return 20;
 
7623
  case MYSQL_TYPE_INT24:
 
7624
    return 8;
 
7625
  default:
 
7626
    DBUG_ASSERT(0); // we should never go there
 
7627
    return 0;
 
7628
  }
 
7629
}
 
7630
 
 
7631
 
 
7632
/**
 
7633
  Make temporary table field according collected information about type
 
7634
  of UNION result.
 
7635
 
 
7636
  @param table  temporary table for which we create fields
 
7637
 
 
7638
  @return
 
7639
    created field
 
7640
*/
 
7641
 
 
7642
Field *Item_type_holder::make_field_by_type(TABLE *table)
 
7643
{
 
7644
  /*
 
7645
    The field functions defines a field to be not null if null_ptr is not 0
 
7646
  */
 
7647
  uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
 
7648
  Field *field;
 
7649
 
 
7650
  switch (fld_type) {
 
7651
  case MYSQL_TYPE_ENUM:
 
7652
    DBUG_ASSERT(enum_set_typelib);
 
7653
    field= new Field_enum((uchar *) 0, max_length, null_ptr, 0,
 
7654
                          Field::NONE, name,
 
7655
                          get_enum_pack_length(enum_set_typelib->count),
 
7656
                          enum_set_typelib, collation.collation);
 
7657
    if (field)
 
7658
      field->init(table);
 
7659
    return field;
 
7660
  case MYSQL_TYPE_SET:
 
7661
    DBUG_ASSERT(enum_set_typelib);
 
7662
    field= new Field_set((uchar *) 0, max_length, null_ptr, 0,
 
7663
                         Field::NONE, name,
 
7664
                         get_set_pack_length(enum_set_typelib->count),
 
7665
                         enum_set_typelib, collation.collation);
 
7666
    if (field)
 
7667
      field->init(table);
 
7668
    return field;
 
7669
  case MYSQL_TYPE_NULL:
 
7670
    return make_string_field(table);
 
7671
  default:
 
7672
    break;
 
7673
  }
 
7674
  return tmp_table_field_from_field_type(table, 0);
 
7675
}
 
7676
 
 
7677
 
 
7678
/**
 
7679
  Get full information from Item about enum/set fields to be able to create
 
7680
  them later.
 
7681
 
 
7682
  @param item    Item for information collection
 
7683
*/
 
7684
void Item_type_holder::get_full_info(Item *item)
 
7685
{
 
7686
  if (fld_type == MYSQL_TYPE_ENUM ||
 
7687
      fld_type == MYSQL_TYPE_SET)
 
7688
  {
 
7689
    if (item->type() == Item::SUM_FUNC_ITEM &&
 
7690
        (((Item_sum*)item)->sum_func() == Item_sum::MAX_FUNC ||
 
7691
         ((Item_sum*)item)->sum_func() == Item_sum::MIN_FUNC))
 
7692
      item = ((Item_sum*)item)->get_arg(0);
 
7693
    /*
 
7694
      We can have enum/set type after merging only if we have one enum|set
 
7695
      field (or MIN|MAX(enum|set field)) and number of NULL fields
 
7696
    */
 
7697
    DBUG_ASSERT((enum_set_typelib &&
 
7698
                 get_real_type(item) == MYSQL_TYPE_NULL) ||
 
7699
                (!enum_set_typelib &&
 
7700
                 item->type() == Item::FIELD_ITEM &&
 
7701
                 (get_real_type(item) == MYSQL_TYPE_ENUM ||
 
7702
                  get_real_type(item) == MYSQL_TYPE_SET) &&
 
7703
                 ((Field_enum*)((Item_field *) item)->field)->typelib));
 
7704
    if (!enum_set_typelib)
 
7705
    {
 
7706
      enum_set_typelib= ((Field_enum*)((Item_field *) item)->field)->typelib;
 
7707
    }
 
7708
  }
 
7709
}
 
7710
 
 
7711
 
 
7712
double Item_type_holder::val_real()
 
7713
{
 
7714
  DBUG_ASSERT(0); // should never be called
 
7715
  return 0.0;
 
7716
}
 
7717
 
 
7718
 
 
7719
longlong Item_type_holder::val_int()
 
7720
{
 
7721
  DBUG_ASSERT(0); // should never be called
 
7722
  return 0;
 
7723
}
 
7724
 
 
7725
my_decimal *Item_type_holder::val_decimal(my_decimal *)
 
7726
{
 
7727
  DBUG_ASSERT(0); // should never be called
 
7728
  return 0;
 
7729
}
 
7730
 
 
7731
String *Item_type_holder::val_str(String*)
 
7732
{
 
7733
  DBUG_ASSERT(0); // should never be called
 
7734
  return 0;
 
7735
}
 
7736
 
 
7737
void Item_result_field::cleanup()
 
7738
{
 
7739
  DBUG_ENTER("Item_result_field::cleanup()");
 
7740
  Item::cleanup();
 
7741
  result_field= 0;
 
7742
  DBUG_VOID_RETURN;
 
7743
}
 
7744
 
 
7745
/**
 
7746
  Dummy error processor used by default by Name_resolution_context.
 
7747
 
 
7748
  @note
 
7749
    do nothing
 
7750
*/
 
7751
 
 
7752
void dummy_error_processor(THD *thd, void *data)
 
7753
{}
 
7754
 
 
7755
/**
 
7756
  Wrapper of hide_view_error call for Name_resolution_context error
 
7757
  processor.
 
7758
 
 
7759
  @note
 
7760
    hide view underlying tables details in error messages
 
7761
*/
 
7762
 
 
7763
void view_error_processor(THD *thd, void *data)
 
7764
{
 
7765
  ((TABLE_LIST *)data)->hide_view_error(thd);
 
7766
}
 
7767
 
 
7768
/*****************************************************************************
 
7769
** Instantiate templates
 
7770
*****************************************************************************/
 
7771
 
 
7772
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
7773
template class List<Item>;
 
7774
template class List_iterator<Item>;
 
7775
template class List_iterator_fast<Item>;
 
7776
template class List_iterator_fast<Item_field>;
 
7777
template class List<List_item>;
 
7778
#endif