~drizzle-trunk/drizzle/development

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