~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/item.cc

Fixed depend problem

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