~linuxjedi/drizzle/trunk-bug-667053

« back to all changes in this revision

Viewing changes to sql/item.cc

  • Committer: brian
  • Date: 2008-06-25 05:29:13 UTC
  • Revision ID: brian@localhost.localdomain-20080625052913-6upwo0jsrl4lnapl
clean slate

Show diffs side-by-side

added added

removed removed

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