~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/item.cc

Removed dead variable, sorted authors file.

Show diffs side-by-side

added added

removed removed

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