~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/item.cc

  • Committer: Mark Atwood
  • Date: 2008-07-12 11:37:59 UTC
  • mto: This revision was merged to the branch mainline in revision 139.
  • Revision ID: me@mark.atwood.name-20080712113759-nrjn1bq1e0shuory
Add hello_world() UDF

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