~ubuntu-branches/ubuntu/saucy/drizzle/saucy-proposed

« back to all changes in this revision

Viewing changes to drizzled/item.cc

  • Committer: Bazaar Package Importer
  • Author(s): Monty Taylor
  • Date: 2010-03-18 12:12:31 UTC
  • Revision ID: james.westby@ubuntu.com-20100318121231-k6g1xe6cshbwa0f8
Tags: upstream-2010.03.1347
ImportĀ upstreamĀ versionĀ 2010.03.1347

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/long.h"
 
45
#include "drizzled/field/int64_t.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 <math.h>
 
53
#include <algorithm>
 
54
#include <float.h>
 
55
 
 
56
using namespace std;
 
57
 
 
58
namespace drizzled
 
59
{
 
60
 
 
61
const String my_null_string("NULL", 4, default_charset_info);
 
62
 
 
63
bool Item::is_expensive_processor(unsigned char *)
 
64
{
 
65
  return false;
 
66
}
 
67
 
 
68
void Item::fix_after_pullout(Select_Lex *, Item **)
 
69
{}
 
70
 
 
71
Field *Item::tmp_table_field(Table *)
 
72
{
 
73
  return NULL;
 
74
}
 
75
 
 
76
const char *Item::full_name(void) const
 
77
{
 
78
  return name ? name : "???";
 
79
}
 
80
 
 
81
int64_t Item::val_int_endpoint(bool, bool *)
 
82
{
 
83
  assert(0);
 
84
  return 0;
 
85
}
 
86
 
 
87
/** @todo Make this functions class dependent */
 
88
bool Item::val_bool()
 
89
{
 
90
  switch(result_type()) 
 
91
  {
 
92
    case INT_RESULT:
 
93
      return val_int() != 0;
 
94
    case DECIMAL_RESULT:
 
95
    {
 
96
      my_decimal decimal_value;
 
97
      my_decimal *val= val_decimal(&decimal_value);
 
98
      if (val)
 
99
        return !my_decimal_is_zero(val);
 
100
      return false;
 
101
    }
 
102
    case REAL_RESULT:
 
103
    case STRING_RESULT:
 
104
      return val_real() != 0.0;
 
105
    case ROW_RESULT:
 
106
    default:
 
107
      assert(0);
 
108
      return false;
 
109
  }
 
110
}
 
111
 
 
112
String *Item::val_string_from_real(String *str)
 
113
{
 
114
  double nr= val_real();
 
115
  if (null_value)
 
116
    return NULL;
 
117
 
 
118
  str->set_real(nr, decimals, &my_charset_bin);
 
119
  return str;
 
120
}
 
121
 
 
122
String *Item::val_string_from_int(String *str)
 
123
{
 
124
  int64_t nr= val_int();
 
125
  if (null_value)
 
126
    return NULL;
 
127
 
 
128
  str->set_int(nr, unsigned_flag, &my_charset_bin);
 
129
  return str;
 
130
}
 
131
 
 
132
String *Item::val_string_from_decimal(String *str)
 
133
{
 
134
  my_decimal dec_buf, *dec= val_decimal(&dec_buf);
 
135
  if (null_value)
 
136
    return NULL;
 
137
 
 
138
  my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, false, &dec_buf);
 
139
  my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
 
140
  return str;
 
141
}
 
142
 
 
143
my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
 
144
{
 
145
  double nr= val_real();
 
146
  if (null_value)
 
147
    return NULL;
 
148
 
 
149
  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
 
150
  return (decimal_value);
 
151
}
 
152
 
 
153
my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
 
154
{
 
155
  int64_t nr= val_int();
 
156
  if (null_value)
 
157
    return NULL;
 
158
 
 
159
  int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
 
160
  return decimal_value;
 
161
}
 
162
 
 
163
my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
 
164
{
 
165
  String *res;
 
166
  char *end_ptr;
 
167
  if (!(res= val_str(&str_value)))
 
168
    return NULL;
 
169
 
 
170
  end_ptr= (char*) res->ptr()+ res->length();
 
171
  if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
 
172
                     res->ptr(), 
 
173
                     res->length(), 
 
174
                     res->charset(),
 
175
                     decimal_value) & E_DEC_BAD_NUM)
 
176
  {
 
177
    push_warning_printf(current_session, 
 
178
                        DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
179
                        ER_TRUNCATED_WRONG_VALUE,
 
180
                        ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
 
181
                        str_value.c_ptr());
 
182
  }
 
183
  return decimal_value;
 
184
}
 
185
 
 
186
my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value)
 
187
{
 
188
  assert(fixed);
 
189
  DRIZZLE_TIME ltime;
 
190
  if (get_date(&ltime, TIME_FUZZY_DATE))
 
191
  {
 
192
    my_decimal_set_zero(decimal_value);
 
193
    null_value= 1;                               // set NULL, stop processing
 
194
    return NULL;
 
195
  }
 
196
  return date2my_decimal(&ltime, decimal_value);
 
197
}
 
198
 
 
199
my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value)
 
200
{
 
201
  assert(fixed);
 
202
  DRIZZLE_TIME ltime;
 
203
  if (get_time(&ltime))
 
204
  {
 
205
    my_decimal_set_zero(decimal_value);
 
206
    return NULL;
 
207
  }
 
208
  return date2my_decimal(&ltime, decimal_value);
 
209
}
 
210
 
 
211
double Item::val_real_from_decimal()
 
212
{
 
213
  /* Note that fix_fields may not be called for Item_avg_field items */
 
214
  double result;
 
215
  my_decimal value_buff, *dec_val= val_decimal(&value_buff);
 
216
  if (null_value)
 
217
    return 0.0;
 
218
  my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
 
219
  return result;
 
220
}
 
221
 
 
222
int64_t Item::val_int_from_decimal()
 
223
{
 
224
  /* Note that fix_fields may not be called for Item_avg_field items */
 
225
  int64_t result;
 
226
  my_decimal value, *dec_val= val_decimal(&value);
 
227
  if (null_value)
 
228
    return 0;
 
229
  my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result);
 
230
  return result;
 
231
}
 
232
 
 
233
int Item::save_time_in_field(Field *field)
 
234
{
 
235
  DRIZZLE_TIME ltime;
 
236
  if (get_time(&ltime))
 
237
    return set_field_to_null(field);
 
238
  field->set_notnull();
 
239
  return field->store_time(&ltime, DRIZZLE_TIMESTAMP_TIME);
 
240
}
 
241
 
 
242
int Item::save_date_in_field(Field *field)
 
243
{
 
244
  DRIZZLE_TIME ltime;
 
245
  if (get_date(&ltime, TIME_FUZZY_DATE))
 
246
    return set_field_to_null(field);
 
247
  field->set_notnull();
 
248
  return field->store_time(&ltime, DRIZZLE_TIMESTAMP_DATETIME);
 
249
}
 
250
 
 
251
/**
 
252
 * Check if the Item is null and stores the NULL or the
 
253
 * result value in the field accordingly.
 
254
 */
 
255
int Item::save_str_value_in_field(Field *field, String *result)
 
256
{
 
257
  if (null_value)
 
258
    return set_field_to_null(field);
 
259
  field->set_notnull();
 
260
  return field->store(result->ptr(), result->length(), collation.collation);
 
261
}
 
262
 
 
263
Item::Item():
 
264
  is_expensive_cache(-1),
 
265
  name(0), 
 
266
  name_length(0),
 
267
  orig_name(0), 
 
268
  max_length(0), 
 
269
  marker(0),
 
270
  decimals(0),
 
271
  fixed(false),
 
272
  maybe_null(false),
 
273
  null_value(false),
 
274
  unsigned_flag(false), 
 
275
  with_sum_func(false),
 
276
  is_autogenerated_name(true),
 
277
  with_subselect(false),
 
278
  collation(&my_charset_bin, DERIVATION_COERCIBLE)
 
279
{
 
280
  cmp_context= (Item_result)-1;
 
281
 
 
282
  /* Put item in free list so that we can free all items at end */
 
283
  Session *session= current_session;
 
284
  next= session->free_list;
 
285
  session->free_list= this;
 
286
 
 
287
  /*
 
288
    Item constructor can be called during execution other then SQL_COM
 
289
    command => we should check session->lex->current_select on zero (session->lex
 
290
    can be uninitialised)
 
291
  */
 
292
  if (session->lex->current_select)
 
293
  {
 
294
    enum_parsing_place place= session->lex->current_select->parsing_place;
 
295
    if (place == SELECT_LIST || place == IN_HAVING)
 
296
      session->lex->current_select->select_n_having_items++;
 
297
  }
 
298
}
 
299
 
 
300
Item::Item(Session *session, Item *item):
 
301
  is_expensive_cache(-1),
 
302
  str_value(item->str_value),
 
303
  name(item->name),
 
304
  name_length(item->name_length),
 
305
  orig_name(item->orig_name),
 
306
  max_length(item->max_length),
 
307
  marker(item->marker),
 
308
  decimals(item->decimals),
 
309
  fixed(item->fixed),
 
310
  maybe_null(item->maybe_null),
 
311
  null_value(item->null_value),
 
312
  unsigned_flag(item->unsigned_flag),
 
313
  with_sum_func(item->with_sum_func),
 
314
  is_autogenerated_name(item->is_autogenerated_name),
 
315
  with_subselect(item->with_subselect),
 
316
  collation(item->collation),
 
317
  cmp_context(item->cmp_context)
 
318
{
 
319
  /* Put this item in the session's free list */
 
320
  next= session->free_list;
 
321
  session->free_list= this;
 
322
}
 
323
 
 
324
uint32_t Item::float_length(uint32_t decimals_par) const
 
325
{
 
326
  return decimals != NOT_FIXED_DEC ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;
 
327
}
 
328
 
 
329
uint32_t Item::decimal_precision() const
 
330
{
 
331
  Item_result restype= result_type();
 
332
 
 
333
  if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
 
334
    return min(my_decimal_length_to_precision(max_length, decimals, unsigned_flag),
 
335
               (uint32_t) DECIMAL_MAX_PRECISION);
 
336
  return min(max_length, (uint32_t) DECIMAL_MAX_PRECISION);
 
337
}
 
338
 
 
339
int Item::decimal_int_part() const
 
340
{
 
341
  return my_decimal_int_part(decimal_precision(), decimals);
 
342
}
 
343
 
 
344
void Item::print(String *str, enum_query_type)
 
345
{
 
346
  str->append(full_name());
 
347
}
 
348
 
 
349
void Item::print_item_w_name(String *str, enum_query_type query_type)
 
350
{
 
351
  print(str, query_type);
 
352
 
 
353
  if (name)
 
354
  {
 
355
    str->append(STRING_WITH_LEN(" AS "));
 
356
    str->append_identifier(name, (uint32_t) strlen(name));
 
357
  }
 
358
}
 
359
 
 
360
void Item::split_sum_func(Session *, Item **, List<Item> &)
 
361
{}
 
362
 
 
363
void Item::cleanup()
 
364
{
 
365
  fixed= false;
 
366
  marker= 0;
 
367
  if (orig_name)
 
368
    name= orig_name;
 
369
  return;
 
370
}
 
371
 
 
372
void Item::rename(char *new_name)
 
373
{
 
374
  /*
 
375
    we can compare pointers to names here, because if name was not changed,
 
376
    pointer will be same
 
377
  */
 
378
  if (! orig_name && new_name != name)
 
379
    orig_name= name;
 
380
  name= new_name;
 
381
}
 
382
 
 
383
Item* Item::transform(Item_transformer transformer, unsigned char *arg)
 
384
{
 
385
  return (this->*transformer)(arg);
 
386
}
 
387
 
 
388
bool Item::check_cols(uint32_t c)
 
389
{
 
390
  if (c != 1)
 
391
  {
 
392
    my_error(ER_OPERAND_COLUMNS, MYF(0), c);
 
393
    return true;
 
394
  }
 
395
  return false;
 
396
}
 
397
 
 
398
void Item::set_name(const char *str, uint32_t length, const CHARSET_INFO * const cs)
 
399
{
 
400
  if (!length)
 
401
  {
 
402
    /* Empty string, used by AS or internal function like last_insert_id() */
 
403
    name= (char*) str;
 
404
    name_length= 0;
 
405
    return;
 
406
  }
 
407
  if (cs->ctype)
 
408
  {
 
409
    uint32_t orig_len= length;
 
410
    while (length && ! my_isgraph(cs, *str))
 
411
    {
 
412
      /* Fix problem with yacc */
 
413
      length--;
 
414
      str++;
 
415
    }
 
416
    if (orig_len != length && ! is_autogenerated_name)
 
417
    {
 
418
      if (length == 0)
 
419
        push_warning_printf(current_session, 
 
420
                            DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
421
                            ER_NAME_BECOMES_EMPTY, 
 
422
                            ER(ER_NAME_BECOMES_EMPTY),
 
423
                            str + length - orig_len);
 
424
      else
 
425
        push_warning_printf(current_session, 
 
426
                            DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
427
                            ER_REMOVED_SPACES, 
 
428
                            ER(ER_REMOVED_SPACES),
 
429
                            str + length - orig_len);
 
430
    }
 
431
  }
 
432
  name= memory::sql_strmake(str, length);
 
433
}
 
434
 
 
435
bool Item::eq(const Item *item, bool) const
 
436
{
 
437
  /*
 
438
    Note, that this is never true if item is a Item_param:
 
439
    for all basic constants we have special checks, and Item_param's
 
440
    type() can be only among basic constant types.
 
441
  */
 
442
  return type() == item->type() && 
 
443
         name && 
 
444
         item->name &&
 
445
         ! my_strcasecmp(system_charset_info, name, item->name);
 
446
}
 
447
 
 
448
Item *Item::safe_charset_converter(const CHARSET_INFO * const tocs)
 
449
{
 
450
  Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1);
 
451
  return conv->safe ? conv : NULL;
 
452
}
 
453
 
 
454
bool Item::get_date(DRIZZLE_TIME *ltime,uint32_t fuzzydate)
 
455
{
 
456
  if (result_type() == STRING_RESULT)
 
457
  {
 
458
    char buff[40];
 
459
    String tmp(buff,sizeof(buff), &my_charset_bin),*res;
 
460
    if (!(res=val_str(&tmp)) ||
 
461
        str_to_datetime_with_warn(res->ptr(), res->length(),
 
462
                                  ltime, fuzzydate) <= DRIZZLE_TIMESTAMP_ERROR)
 
463
      goto err;
 
464
  }
 
465
  else
 
466
  {
 
467
    int64_t value= val_int();
 
468
    int was_cut;
 
469
    if (number_to_datetime(value, ltime, fuzzydate, &was_cut) == -1L)
 
470
    {
 
471
      char buff[22], *end;
 
472
      end= internal::int64_t10_to_str(value, buff, -10);
 
473
      make_truncated_value_warning(current_session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
474
                                   buff, (int) (end-buff), DRIZZLE_TIMESTAMP_NONE,
 
475
                                   NULL);
 
476
      goto err;
 
477
    }
 
478
  }
 
479
  return false;
 
480
 
 
481
err:
 
482
  memset(ltime, 0, sizeof(*ltime));
 
483
  return true;
 
484
}
 
485
 
 
486
bool Item::get_time(DRIZZLE_TIME *ltime)
 
487
{
 
488
  char buff[40];
 
489
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
 
490
  if (!(res=val_str(&tmp)) ||
 
491
      str_to_time_with_warn(res->ptr(), res->length(), ltime))
 
492
  {
 
493
    memset(ltime, 0, sizeof(*ltime));
 
494
    return true;
 
495
  }
 
496
  return false;
 
497
}
 
498
 
 
499
bool Item::get_date_result(DRIZZLE_TIME *ltime,uint32_t fuzzydate)
 
500
{
 
501
  return get_date(ltime,fuzzydate);
 
502
}
 
503
 
 
504
bool Item::is_null()
 
505
{
 
506
  return false;
 
507
}
 
508
 
 
509
void Item::update_null_value ()
 
510
{
 
511
  (void) val_int();
 
512
}
 
513
 
 
514
void Item::top_level_item(void)
 
515
{}
 
516
 
 
517
void Item::set_result_field(Field *)
 
518
{}
 
519
 
 
520
bool Item::is_result_field(void)
 
521
{
 
522
  return false;
 
523
}
 
524
 
 
525
bool Item::is_bool_func(void)
 
526
{
 
527
  return false;
 
528
}
 
529
 
 
530
void Item::save_in_result_field(bool)
 
531
{}
 
532
 
 
533
void Item::no_rows_in_result(void)
 
534
{}
 
535
 
 
536
Item *Item::copy_or_same(Session *)
 
537
{
 
538
  return this;
 
539
}
 
540
 
 
541
Item *Item::copy_andor_structure(Session *)
 
542
{
 
543
  return this;
 
544
}
 
545
 
 
546
Item *Item::real_item(void)
 
547
{
 
548
  return this;
 
549
}
 
550
 
 
551
const Item *Item::real_item(void) const
 
552
{
 
553
  return this;
 
554
}
 
555
 
 
556
Item *Item::get_tmp_table_item(Session *session)
 
557
{
 
558
  return copy_or_same(session);
 
559
}
 
560
 
 
561
const CHARSET_INFO *Item::default_charset()
 
562
{
 
563
  return current_session->variables.getCollation();
 
564
}
 
565
 
 
566
const CHARSET_INFO *Item::compare_collation()
 
567
{
 
568
  return NULL;
 
569
}
 
570
 
 
571
bool Item::walk(Item_processor processor, bool, unsigned char *arg)
 
572
{
 
573
  return (this->*processor)(arg);
 
574
}
 
575
 
 
576
Item* Item::compile(Item_analyzer analyzer, 
 
577
                    unsigned char **arg_p,
 
578
                    Item_transformer transformer, 
 
579
                    unsigned char *arg_t)
 
580
{
 
581
  if ((this->*analyzer) (arg_p))
 
582
    return ((this->*transformer) (arg_t));
 
583
  return NULL;
 
584
}
 
585
 
 
586
void Item::traverse_cond(Cond_traverser traverser, void *arg, traverse_order)
 
587
{
 
588
  (*traverser)(this, arg);
 
589
}
 
590
 
 
591
bool Item::remove_dependence_processor(unsigned char *)
 
592
{
 
593
  return false;
 
594
}
 
595
 
 
596
bool Item::remove_fixed(unsigned char *)
 
597
{
 
598
  fixed= false;
 
599
  return false;
 
600
}
 
601
 
 
602
bool Item::collect_item_field_processor(unsigned char *)
 
603
{
 
604
  return false;
 
605
}
 
606
 
 
607
bool Item::find_item_in_field_list_processor(unsigned char *)
 
608
{
 
609
  return false;
 
610
}
 
611
 
 
612
bool Item::change_context_processor(unsigned char *)
 
613
{
 
614
  return false;
 
615
}
 
616
 
 
617
bool Item::register_field_in_read_map(unsigned char *)
 
618
{
 
619
  return false;
 
620
}
 
621
 
 
622
bool Item::subst_argument_checker(unsigned char **arg)
 
623
{
 
624
  if (*arg)
 
625
    *arg= NULL;
 
626
  return true;
 
627
}
 
628
 
 
629
Item *Item::equal_fields_propagator(unsigned char *)
 
630
{
 
631
  return this;
 
632
}
 
633
 
 
634
bool Item::set_no_const_sub(unsigned char *)
 
635
{
 
636
  return false;
 
637
}
 
638
 
 
639
Item *Item::replace_equal_field(unsigned char *)
 
640
{
 
641
  return this;
 
642
}
 
643
 
 
644
uint32_t Item::cols()
 
645
{
 
646
  return 1;
 
647
}
 
648
 
 
649
Item* Item::element_index(uint32_t)
 
650
{
 
651
  return this;
 
652
}
 
653
 
 
654
Item** Item::addr(uint32_t)
 
655
{
 
656
  return NULL;
 
657
}
 
658
 
 
659
bool Item::null_inside()
 
660
{
 
661
  return false;
 
662
}
 
663
 
 
664
void Item::bring_value()
 
665
{}
 
666
 
 
667
Item *Item::neg_transformer(Session *)
 
668
{
 
669
  return NULL;
 
670
}
 
671
 
 
672
Item *Item::update_value_transformer(unsigned char *)
 
673
{
 
674
  return this;
 
675
}
 
676
 
 
677
void Item::delete_self()
 
678
{
 
679
  cleanup();
 
680
  delete this;
 
681
}
 
682
 
 
683
bool Item::result_as_int64_t()
 
684
{
 
685
  return false;
 
686
}
 
687
 
 
688
bool Item::is_expensive()
 
689
{
 
690
  if (is_expensive_cache < 0)
 
691
    is_expensive_cache= walk(&Item::is_expensive_processor, 0,
 
692
                             (unsigned char*)0);
 
693
  return test(is_expensive_cache);
 
694
}
 
695
 
 
696
/*
 
697
 need a special class to adjust printing : references to aggregate functions
 
698
 must not be printed as refs because the aggregate functions that are added to
 
699
 the front of select list are not printed as well.
 
700
*/
 
701
class Item_aggregate_ref : public Item_ref
 
702
{
 
703
public:
 
704
  Item_aggregate_ref(Name_resolution_context *context_arg, Item **item,
 
705
                  const char *table_name_arg, const char *field_name_arg)
 
706
    :Item_ref(context_arg, item, table_name_arg, field_name_arg) {}
 
707
 
 
708
  virtual inline void print (String *str, enum_query_type query_type)
 
709
  {
 
710
    if (ref)
 
711
      (*ref)->print(str, query_type);
 
712
    else
 
713
      Item_ident::print(str, query_type);
 
714
  }
 
715
};
 
716
 
 
717
void Item::split_sum_func(Session *session, Item **ref_pointer_array,
 
718
                          List<Item> &fields, Item **ref,
 
719
                          bool skip_registered)
 
720
{
 
721
  /* An item of type Item_sum  is registered <=> ref_by != 0 */
 
722
  if (type() == SUM_FUNC_ITEM && 
 
723
      skip_registered &&
 
724
      ((Item_sum *) this)->ref_by)
 
725
    return;
 
726
 
 
727
  if ((type() != SUM_FUNC_ITEM && with_sum_func) ||
 
728
      (type() == FUNC_ITEM &&
 
729
       (((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC ||
 
730
        ((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC)))
 
731
  {
 
732
    /* Will split complicated items and ignore simple ones */
 
733
    split_sum_func(session, ref_pointer_array, fields);
 
734
  }
 
735
  else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) &&
 
736
           type() != SUBSELECT_ITEM &&
 
737
           type() != REF_ITEM)
 
738
  {
 
739
    /*
 
740
      Replace item with a reference so that we can easily calculate
 
741
      it (in case of sum functions) or copy it (in case of fields)
 
742
 
 
743
      The test above is to ensure we don't do a reference for things
 
744
      that are constants (PARAM_TABLE_BIT is in effect a constant)
 
745
      or already referenced (for example an item in HAVING)
 
746
      Exception is Item_direct_view_ref which we need to convert to
 
747
      Item_ref to allow fields from view being stored in tmp table.
 
748
    */
 
749
    Item_aggregate_ref *item_ref;
 
750
    uint32_t el= fields.elements;
 
751
    Item *real_itm= real_item();
 
752
 
 
753
    ref_pointer_array[el]= real_itm;
 
754
    if (!(item_ref= new Item_aggregate_ref(&session->lex->current_select->context,
 
755
                                           ref_pointer_array + el, 0, name)))
 
756
      return; /* fatal_error is set */
 
757
    if (type() == SUM_FUNC_ITEM)
 
758
      item_ref->depended_from= ((Item_sum *) this)->depended_from();
 
759
    fields.push_front(real_itm);
 
760
    session->change_item_tree(ref, item_ref);
 
761
  }
 
762
}
 
763
 
 
764
/*
 
765
  Functions to convert item to field (for send_fields)
 
766
*/
 
767
bool Item::fix_fields(Session *, Item **)
 
768
{
 
769
  /* We do not check fields which are fixed during construction */
 
770
  assert(! fixed || basic_const_item());
 
771
  fixed= true;
 
772
  return false;
 
773
}
 
774
 
 
775
void mark_as_dependent(Session *session, Select_Lex *last, Select_Lex *current,
 
776
                              Item_ident *resolved_item,
 
777
                              Item_ident *mark_item)
 
778
{
 
779
  const char *db_name= (resolved_item->db_name ?
 
780
                        resolved_item->db_name : "");
 
781
  const char *table_name= (resolved_item->table_name ?
 
782
                           resolved_item->table_name : "");
 
783
  /* store pointer on Select_Lex from which item is dependent */
 
784
  if (mark_item)
 
785
    mark_item->depended_from= last;
 
786
  current->mark_as_dependent(last);
 
787
  if (session->lex->describe & DESCRIBE_EXTENDED)
 
788
  {
 
789
    char warn_buff[DRIZZLE_ERRMSG_SIZE];
 
790
    sprintf(warn_buff, ER(ER_WARN_FIELD_RESOLVED),
 
791
            db_name, (db_name[0] ? "." : ""),
 
792
            table_name, (table_name [0] ? "." : ""),
 
793
            resolved_item->field_name,
 
794
            current->select_number, last->select_number);
 
795
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
796
                 ER_WARN_FIELD_RESOLVED, warn_buff);
 
797
  }
 
798
}
 
799
 
 
800
void mark_select_range_as_dependent(Session *session,
 
801
                                    Select_Lex *last_select,
 
802
                                    Select_Lex *current_sel,
 
803
                                    Field *found_field, Item *found_item,
 
804
                                    Item_ident *resolved_item)
 
805
{
 
806
  /*
 
807
    Go from current SELECT to SELECT where field was resolved (it
 
808
    have to be reachable from current SELECT, because it was already
 
809
    done once when we resolved this field and cached result of
 
810
    resolving)
 
811
  */
 
812
  Select_Lex *previous_select= current_sel;
 
813
  for (; previous_select->outer_select() != last_select;
 
814
       previous_select= previous_select->outer_select())
 
815
  {
 
816
    Item_subselect *prev_subselect_item= previous_select->master_unit()->item;
 
817
    prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
 
818
    prev_subselect_item->const_item_cache= 0;
 
819
  }
 
820
  {
 
821
    Item_subselect *prev_subselect_item= previous_select->master_unit()->item;
 
822
    Item_ident *dependent= resolved_item;
 
823
    if (found_field == view_ref_found)
 
824
    {
 
825
      Item::Type type= found_item->type();
 
826
      prev_subselect_item->used_tables_cache|= found_item->used_tables();
 
827
      dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
 
828
                  (Item_ident*) found_item :
 
829
                  0);
 
830
    }
 
831
    else
 
832
      prev_subselect_item->used_tables_cache|= found_field->table->map;
 
833
    prev_subselect_item->const_item_cache= 0;
 
834
    mark_as_dependent(session, last_select, current_sel, resolved_item,
 
835
                      dependent);
 
836
  }
 
837
}
 
838
 
 
839
/**
 
840
  Search a GROUP BY clause for a field with a certain name.
 
841
 
 
842
  Search the GROUP BY list for a column named as find_item. When searching
 
843
  preference is given to columns that are qualified with the same table (and
 
844
  database) name as the one being searched for.
 
845
 
 
846
  @param find_item     the item being searched for
 
847
  @param group_list    GROUP BY clause
 
848
 
 
849
  @return
 
850
    - the found item on success
 
851
    - NULL if find_item is not in group_list
 
852
*/
 
853
static Item** find_field_in_group_list(Item *find_item, order_st *group_list)
 
854
{
 
855
  const char *db_name;
 
856
  const char *table_name;
 
857
  const char *field_name;
 
858
  order_st *found_group= NULL;
 
859
  int found_match_degree= 0;
 
860
  Item_ident *cur_field;
 
861
  int cur_match_degree= 0;
 
862
  char name_buff[NAME_LEN+1];
 
863
 
 
864
  if (find_item->type() == Item::FIELD_ITEM ||
 
865
      find_item->type() == Item::REF_ITEM)
 
866
  {
 
867
    db_name= ((Item_ident*) find_item)->db_name;
 
868
    table_name= ((Item_ident*) find_item)->table_name;
 
869
    field_name= ((Item_ident*) find_item)->field_name;
 
870
  }
 
871
  else
 
872
    return NULL;
 
873
 
 
874
  if (db_name)
 
875
  {
 
876
    /* Convert database to lower case for comparison */
 
877
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
 
878
    my_casedn_str(files_charset_info, name_buff);
 
879
    db_name= name_buff;
 
880
  }
 
881
 
 
882
  assert(field_name != 0);
 
883
 
 
884
  for (order_st *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
 
885
  {
 
886
    if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM)
 
887
    {
 
888
      cur_field= (Item_ident*) *cur_group->item;
 
889
      cur_match_degree= 0;
 
890
 
 
891
      assert(cur_field->field_name != 0);
 
892
 
 
893
      if (! my_strcasecmp(system_charset_info, cur_field->field_name, field_name))
 
894
        ++cur_match_degree;
 
895
      else
 
896
        continue;
 
897
 
 
898
      if (cur_field->table_name && table_name)
 
899
      {
 
900
        /* If field_name is qualified by a table name. */
 
901
        if (my_strcasecmp(table_alias_charset, cur_field->table_name, table_name))
 
902
          /* Same field names, different tables. */
 
903
          return NULL;
 
904
 
 
905
        ++cur_match_degree;
 
906
        if (cur_field->db_name && db_name)
 
907
        {
 
908
          /* If field_name is also qualified by a database name. */
 
909
          if (strcmp(cur_field->db_name, db_name))
 
910
            /* Same field names, different databases. */
 
911
            return NULL;
 
912
          ++cur_match_degree;
 
913
        }
 
914
      }
 
915
 
 
916
      if (cur_match_degree > found_match_degree)
 
917
      {
 
918
        found_match_degree= cur_match_degree;
 
919
        found_group= cur_group;
 
920
      }
 
921
      else if (found_group &&
 
922
               (cur_match_degree == found_match_degree) &&
 
923
               ! (*(found_group->item))->eq(cur_field, 0))
 
924
      {
 
925
        /*
 
926
          If the current resolve candidate matches equally well as the current
 
927
          best match, they must reference the same column, otherwise the field
 
928
          is ambiguous.
 
929
        */
 
930
        my_error(ER_NON_UNIQ_ERROR, MYF(0), find_item->full_name(), current_session->where);
 
931
        return NULL;
 
932
      }
 
933
    }
 
934
  }
 
935
 
 
936
  if (found_group)
 
937
    return found_group->item;
 
938
  else
 
939
    return NULL;
 
940
}
 
941
 
 
942
Item** resolve_ref_in_select_and_group(Session *session, Item_ident *ref, Select_Lex *select)
 
943
{
 
944
  Item **group_by_ref= NULL;
 
945
  Item **select_ref= NULL;
 
946
  order_st *group_list= (order_st*) select->group_list.first;
 
947
  bool ambiguous_fields= false;
 
948
  uint32_t counter;
 
949
  enum_resolution_type resolution;
 
950
 
 
951
  /*
 
952
    Search for a column or derived column named as 'ref' in the SELECT
 
953
    clause of the current select.
 
954
  */
 
955
  if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()),
 
956
                                      &counter, REPORT_EXCEPT_NOT_FOUND,
 
957
                                      &resolution)))
 
958
    return NULL; /* Some error occurred. */
 
959
  if (resolution == RESOLVED_AGAINST_ALIAS)
 
960
    ref->alias_name_used= true;
 
961
 
 
962
  /* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
 
963
  if (select->having_fix_field && !ref->with_sum_func && group_list)
 
964
  {
 
965
    group_by_ref= find_field_in_group_list(ref, group_list);
 
966
 
 
967
    /* Check if the fields found in SELECT and GROUP BY are the same field. */
 
968
    if (group_by_ref && (select_ref != not_found_item) &&
 
969
        !((*group_by_ref)->eq(*select_ref, 0)))
 
970
    {
 
971
      ambiguous_fields= true;
 
972
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
 
973
                          ER(ER_NON_UNIQ_ERROR), ref->full_name(),
 
974
                          current_session->where);
 
975
 
 
976
    }
 
977
  }
 
978
 
 
979
  if (select_ref != not_found_item || group_by_ref)
 
980
  {
 
981
    if (select_ref != not_found_item && !ambiguous_fields)
 
982
    {
 
983
      assert(*select_ref != 0);
 
984
      if (!select->ref_pointer_array[counter])
 
985
      {
 
986
        my_error(ER_ILLEGAL_REFERENCE, MYF(0),
 
987
                 ref->name, "forward reference in item list");
 
988
        return NULL;
 
989
      }
 
990
      assert((*select_ref)->fixed);
 
991
      return (select->ref_pointer_array + counter);
 
992
    }
 
993
    if (group_by_ref)
 
994
      return group_by_ref;
 
995
    assert(false);
 
996
    return NULL; /* So there is no compiler warning. */
 
997
  }
 
998
 
 
999
  return (Item**) not_found_item;
 
1000
}
 
1001
 
 
1002
void Item::init_make_field(SendField *tmp_field,
 
1003
                           enum enum_field_types field_type_arg)
 
1004
{
 
1005
  char *empty_name= (char*) "";
 
1006
  tmp_field->db_name=   empty_name;
 
1007
  tmp_field->org_table_name= empty_name;
 
1008
  tmp_field->org_col_name= empty_name;
 
1009
  tmp_field->table_name= empty_name;
 
1010
  tmp_field->col_name= name;
 
1011
  tmp_field->charsetnr= collation.collation->number;
 
1012
  tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
 
1013
                    (my_binary_compare(collation.collation) ?
 
1014
                      BINARY_FLAG : 0);
 
1015
  tmp_field->type= field_type_arg;
 
1016
  tmp_field->length= max_length;
 
1017
  tmp_field->decimals= decimals;
 
1018
}
 
1019
 
 
1020
void Item::make_field(SendField *tmp_field)
 
1021
{
 
1022
  init_make_field(tmp_field, field_type());
 
1023
}
 
1024
 
 
1025
enum_field_types Item::string_field_type() const
 
1026
{
 
1027
  enum_field_types f_type= DRIZZLE_TYPE_VARCHAR;
 
1028
  if (max_length >= 65536)
 
1029
    f_type= DRIZZLE_TYPE_BLOB;
 
1030
  return f_type;
 
1031
}
 
1032
 
 
1033
enum_field_types Item::field_type() const
 
1034
{
 
1035
  switch (result_type()) {
 
1036
  case STRING_RESULT:  
 
1037
    return string_field_type();
 
1038
  case INT_RESULT:     
 
1039
    return DRIZZLE_TYPE_LONGLONG;
 
1040
  case DECIMAL_RESULT: 
 
1041
    return DRIZZLE_TYPE_DECIMAL;
 
1042
  case REAL_RESULT:    
 
1043
    return DRIZZLE_TYPE_DOUBLE;
 
1044
  case ROW_RESULT:
 
1045
  default:
 
1046
    assert(0);
 
1047
    return DRIZZLE_TYPE_VARCHAR;
 
1048
  }
 
1049
}
 
1050
 
 
1051
bool Item::is_datetime()
 
1052
{
 
1053
  switch (field_type())
 
1054
  {
 
1055
    case DRIZZLE_TYPE_DATE:
 
1056
    case DRIZZLE_TYPE_DATETIME:
 
1057
    case DRIZZLE_TYPE_TIMESTAMP:
 
1058
      return true;
 
1059
    default:
 
1060
      break;
 
1061
  }
 
1062
  return false;
 
1063
}
 
1064
 
 
1065
String *Item::check_well_formed_result(String *str, bool send_error)
 
1066
{
 
1067
  /* Check whether we got a well-formed string */
 
1068
  const CHARSET_INFO * const cs= str->charset();
 
1069
  int well_formed_error;
 
1070
  uint32_t wlen= cs->cset->well_formed_len(cs,
 
1071
                                       str->ptr(), str->ptr() + str->length(),
 
1072
                                       str->length(), &well_formed_error);
 
1073
  if (wlen < str->length())
 
1074
  {
 
1075
    Session *session= current_session;
 
1076
    char hexbuf[7];
 
1077
    enum DRIZZLE_ERROR::enum_warning_level level;
 
1078
    uint32_t diff= str->length() - wlen;
 
1079
    set_if_smaller(diff, 3U);
 
1080
    (void) drizzled_string_to_hex(hexbuf, str->ptr() + wlen, diff);
 
1081
    if (send_error)
 
1082
    {
 
1083
      my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
 
1084
               cs->csname,  hexbuf);
 
1085
      return NULL;
 
1086
    }
 
1087
    {
 
1088
      level= DRIZZLE_ERROR::WARN_LEVEL_ERROR;
 
1089
      null_value= 1;
 
1090
      str= 0;
 
1091
    }
 
1092
    push_warning_printf(session, level, ER_INVALID_CHARACTER_STRING,
 
1093
                        ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
 
1094
  }
 
1095
  return str;
 
1096
}
 
1097
 
 
1098
bool Item::eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO * const cs)
 
1099
{
 
1100
  const CHARSET_INFO *save_cs= 0;
 
1101
  const CHARSET_INFO *save_item_cs= 0;
 
1102
  if (collation.collation != cs)
 
1103
  {
 
1104
    save_cs= collation.collation;
 
1105
    collation.collation= cs;
 
1106
  }
 
1107
  if (item->collation.collation != cs)
 
1108
  {
 
1109
    save_item_cs= item->collation.collation;
 
1110
    item->collation.collation= cs;
 
1111
  }
 
1112
  bool res= eq(item, binary_cmp);
 
1113
  if (save_cs)
 
1114
    collation.collation= save_cs;
 
1115
  if (save_item_cs)
 
1116
    item->collation.collation= save_item_cs;
 
1117
  return res;
 
1118
}
 
1119
 
 
1120
Field *Item::make_string_field(Table *table)
 
1121
{
 
1122
  Field *field;
 
1123
  assert(collation.collation);
 
1124
  if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB)
 
1125
    field= new Field_blob(max_length, maybe_null, name,
 
1126
                          collation.collation);
 
1127
  else
 
1128
    field= new Field_varstring(max_length, maybe_null, name, table->s,
 
1129
                               collation.collation);
 
1130
 
 
1131
  if (field)
 
1132
    field->init(table);
 
1133
  return field;
 
1134
}
 
1135
 
 
1136
Field *Item::tmp_table_field_from_field_type(Table *table, bool)
 
1137
{
 
1138
  /*
 
1139
    The field functions defines a field to be not null if null_ptr is not 0
 
1140
  */
 
1141
  unsigned char *null_ptr= maybe_null ? (unsigned char*) "" : 0;
 
1142
  Field *field;
 
1143
 
 
1144
  switch (field_type()) {
 
1145
  case DRIZZLE_TYPE_DECIMAL:
 
1146
    field= new Field_decimal((unsigned char*) 0,
 
1147
                                 max_length,
 
1148
                                 null_ptr,
 
1149
                                 0,
 
1150
                                 Field::NONE,
 
1151
                                 name,
 
1152
                                 decimals,
 
1153
                                 0,
 
1154
                                 unsigned_flag);
 
1155
    break;
 
1156
  case DRIZZLE_TYPE_LONG:
 
1157
    field= new Field_long((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE,
 
1158
                          name, 0, unsigned_flag);
 
1159
    break;
 
1160
  case DRIZZLE_TYPE_LONGLONG:
 
1161
    field= new Field_int64_t((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE,
 
1162
                              name, 0, unsigned_flag);
 
1163
    break;
 
1164
  case DRIZZLE_TYPE_DOUBLE:
 
1165
    field= new Field_double((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE,
 
1166
                            name, decimals, 0, unsigned_flag);
 
1167
    break;
 
1168
  case DRIZZLE_TYPE_NULL:
 
1169
    field= new Field_null((unsigned char*) 0, max_length, name, &my_charset_bin);
 
1170
    break;
 
1171
  case DRIZZLE_TYPE_DATE:
 
1172
    field= new Field_date(maybe_null, name, &my_charset_bin);
 
1173
    break;
 
1174
  case DRIZZLE_TYPE_TIMESTAMP:
 
1175
    field= new Field_timestamp(maybe_null, name, &my_charset_bin);
 
1176
    break;
 
1177
  case DRIZZLE_TYPE_DATETIME:
 
1178
    field= new Field_datetime(maybe_null, name, &my_charset_bin);
 
1179
    break;
 
1180
  default:
 
1181
    /* This case should never be chosen */
 
1182
    assert(0);
 
1183
    /* Fall through to make_string_field() */
 
1184
  case DRIZZLE_TYPE_ENUM:
 
1185
  case DRIZZLE_TYPE_VARCHAR:
 
1186
    return make_string_field(table);
 
1187
  case DRIZZLE_TYPE_BLOB:
 
1188
    if (this->type() == Item::TYPE_HOLDER)
 
1189
      field= new Field_blob(max_length, maybe_null, name, collation.collation,
 
1190
                            1);
 
1191
    else
 
1192
      field= new Field_blob(max_length, maybe_null, name, collation.collation);
 
1193
    break;                                      // Blob handled outside of case
 
1194
  }
 
1195
  if (field)
 
1196
    field->init(table);
 
1197
  return field;
 
1198
}
 
1199
 
 
1200
/*
 
1201
  This implementation can lose str_value content, so if the
 
1202
  Item uses str_value to store something, it should
 
1203
  reimplement it's ::save_in_field() as Item_string, for example, does
 
1204
*/
 
1205
int Item::save_in_field(Field *field, bool no_conversions)
 
1206
{
 
1207
  int error;
 
1208
  if (result_type() == STRING_RESULT)
 
1209
  {
 
1210
    String *result;
 
1211
    const CHARSET_INFO * const cs= collation.collation;
 
1212
    char buff[MAX_FIELD_WIDTH];         // Alloc buffer for small columns
 
1213
    str_value.set_quick(buff, sizeof(buff), cs);
 
1214
    result=val_str(&str_value);
 
1215
    if (null_value)
 
1216
    {
 
1217
      str_value.set_quick(0, 0, cs);
 
1218
      return set_field_to_null_with_conversions(field, no_conversions);
 
1219
    }
 
1220
 
 
1221
    /* NOTE: If null_value == false, "result" must be not NULL.  */
 
1222
 
 
1223
    field->set_notnull();
 
1224
    error=field->store(result->ptr(),result->length(),cs);
 
1225
    str_value.set_quick(0, 0, cs);
 
1226
  }
 
1227
  else if (result_type() == REAL_RESULT &&
 
1228
           field->result_type() == STRING_RESULT)
 
1229
  {
 
1230
    double nr= val_real();
 
1231
    if (null_value)
 
1232
      return set_field_to_null_with_conversions(field, no_conversions);
 
1233
    field->set_notnull();
 
1234
    error= field->store(nr);
 
1235
  }
 
1236
  else if (result_type() == REAL_RESULT)
 
1237
  {
 
1238
    double nr= val_real();
 
1239
    if (null_value)
 
1240
      return set_field_to_null(field);
 
1241
    field->set_notnull();
 
1242
    error=field->store(nr);
 
1243
  }
 
1244
  else if (result_type() == DECIMAL_RESULT)
 
1245
  {
 
1246
    my_decimal decimal_value;
 
1247
    my_decimal *value= val_decimal(&decimal_value);
 
1248
    if (null_value)
 
1249
      return set_field_to_null_with_conversions(field, no_conversions);
 
1250
    field->set_notnull();
 
1251
    error=field->store_decimal(value);
 
1252
  }
 
1253
  else
 
1254
  {
 
1255
    int64_t nr=val_int();
 
1256
    if (null_value)
 
1257
      return set_field_to_null_with_conversions(field, no_conversions);
 
1258
    field->set_notnull();
 
1259
    error=field->store(nr, unsigned_flag);
 
1260
  }
 
1261
  return error;
 
1262
}
 
1263
 
 
1264
/**
 
1265
  Check if an item is a constant one and can be cached.
 
1266
 
 
1267
  @param arg [out] TRUE <=> Cache this item.
 
1268
 
 
1269
  @return TRUE  Go deeper in item tree.
 
1270
  @return FALSE Don't go deeper in item tree.
 
1271
*/
 
1272
 
 
1273
bool Item::cache_const_expr_analyzer(unsigned char **arg)
 
1274
{
 
1275
  bool *cache_flag= (bool*)*arg;
 
1276
  if (!*cache_flag)
 
1277
  {
 
1278
    Item *item= real_item();
 
1279
    /*
 
1280
      Cache constant items unless it's a basic constant, constant field or
 
1281
      a subselect (they use their own cache).
 
1282
    */
 
1283
    if (const_item() &&
 
1284
        !(item->basic_const_item() || item->type() == Item::FIELD_ITEM ||
 
1285
          item->type() == SUBSELECT_ITEM ||
 
1286
           /*
 
1287
             Do not cache GET_USER_VAR() function as its const_item() may
 
1288
             return TRUE for the current thread but it still may change
 
1289
             during the execution.
 
1290
           */
 
1291
          (item->type() == Item::FUNC_ITEM &&
 
1292
           ((Item_func*)item)->functype() == Item_func::GUSERVAR_FUNC)))
 
1293
      *cache_flag= true;
 
1294
    return true;
 
1295
  }
 
1296
  return false;
 
1297
}
 
1298
 
 
1299
/**
 
1300
  Cache item if needed.
 
1301
 
 
1302
  @param arg   TRUE <=> Cache this item.
 
1303
 
 
1304
  @return cache if cache needed.
 
1305
  @return this otherwise.
 
1306
*/
 
1307
 
 
1308
Item* Item::cache_const_expr_transformer(unsigned char *arg)
 
1309
{
 
1310
  if (*(bool*)arg)
 
1311
  {
 
1312
    *((bool*)arg)= false;
 
1313
    Item_cache *cache= Item_cache::get_cache(this);
 
1314
    if (!cache)
 
1315
      return NULL;
 
1316
    cache->setup(this);
 
1317
    cache->store(this);
 
1318
    return cache;
 
1319
  }
 
1320
  return this;
 
1321
}
 
1322
 
 
1323
bool Item::send(plugin::Client *client, String *buffer)
 
1324
{
 
1325
  bool result= false;
 
1326
  enum_field_types f_type;
 
1327
 
 
1328
  switch ((f_type=field_type())) {
 
1329
  default:
 
1330
  case DRIZZLE_TYPE_NULL:
 
1331
  case DRIZZLE_TYPE_ENUM:
 
1332
  case DRIZZLE_TYPE_BLOB:
 
1333
  case DRIZZLE_TYPE_VARCHAR:
 
1334
  case DRIZZLE_TYPE_DECIMAL:
 
1335
  {
 
1336
    String *res;
 
1337
    if ((res=val_str(buffer)))
 
1338
      result= client->store(res->ptr(),res->length());
 
1339
    break;
 
1340
  }
 
1341
  case DRIZZLE_TYPE_LONG:
 
1342
  {
 
1343
    int64_t nr;
 
1344
    nr= val_int();
 
1345
    if (!null_value)
 
1346
      result= client->store((int32_t)nr);
 
1347
    break;
 
1348
  }
 
1349
  case DRIZZLE_TYPE_LONGLONG:
 
1350
  {
 
1351
    int64_t nr;
 
1352
    nr= val_int();
 
1353
    if (!null_value)
 
1354
    {
 
1355
      if (unsigned_flag)
 
1356
        result= client->store((uint64_t)nr);
 
1357
      else
 
1358
        result= client->store((int64_t)nr);
 
1359
    }
 
1360
    break;
 
1361
  }
 
1362
  case DRIZZLE_TYPE_DOUBLE:
 
1363
  {
 
1364
    double nr= val_real();
 
1365
    if (!null_value)
 
1366
      result= client->store(nr, decimals, buffer);
 
1367
    break;
 
1368
  }
 
1369
  case DRIZZLE_TYPE_DATETIME:
 
1370
  case DRIZZLE_TYPE_TIMESTAMP:
 
1371
  {
 
1372
    DRIZZLE_TIME tm;
 
1373
    get_date(&tm, TIME_FUZZY_DATE);
 
1374
    if (!null_value)
 
1375
      result= client->store(&tm);
 
1376
    break;
 
1377
  }
 
1378
  }
 
1379
  if (null_value)
 
1380
    result= client->store();
 
1381
  return result;
 
1382
}
 
1383
 
 
1384
Item_result item_cmp_type(Item_result a,Item_result b)
 
1385
{
 
1386
  if (a == STRING_RESULT && b == STRING_RESULT)
 
1387
    return STRING_RESULT;
 
1388
  if (a == INT_RESULT && b == INT_RESULT)
 
1389
    return INT_RESULT;
 
1390
  else if (a == ROW_RESULT || b == ROW_RESULT)
 
1391
    return ROW_RESULT;
 
1392
  if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
 
1393
      (b == INT_RESULT || b == DECIMAL_RESULT))
 
1394
    return DECIMAL_RESULT;
 
1395
  return REAL_RESULT;
 
1396
}
 
1397
 
 
1398
void resolve_const_item(Session *session, Item **ref, Item *comp_item)
 
1399
{
 
1400
  Item *item= *ref;
 
1401
  Item *new_item= NULL;
 
1402
  if (item->basic_const_item())
 
1403
    return; /* Can't be better */
 
1404
  Item_result res_type=item_cmp_type(comp_item->result_type(),
 
1405
                                     item->result_type());
 
1406
  char *name=item->name; /* Alloced by memory::sql_alloc */
 
1407
 
 
1408
  switch (res_type) {
 
1409
  case STRING_RESULT:
 
1410
  {
 
1411
    char buff[MAX_FIELD_WIDTH];
 
1412
    String tmp(buff,sizeof(buff),&my_charset_bin),*result;
 
1413
    result=item->val_str(&tmp);
 
1414
    if (item->null_value)
 
1415
      new_item= new Item_null(name);
 
1416
    else
 
1417
    {
 
1418
      uint32_t length= result->length();
 
1419
      char *tmp_str= memory::sql_strmake(result->ptr(), length);
 
1420
      new_item= new Item_string(name, tmp_str, length, result->charset());
 
1421
    }
 
1422
    break;
 
1423
  }
 
1424
  case INT_RESULT:
 
1425
  {
 
1426
    int64_t result=item->val_int();
 
1427
    uint32_t length=item->max_length;
 
1428
    bool null_value=item->null_value;
 
1429
    new_item= (null_value ? (Item*) new Item_null(name) :
 
1430
               (Item*) new Item_int(name, result, length));
 
1431
    break;
 
1432
  }
 
1433
  case ROW_RESULT:
 
1434
  if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
 
1435
  {
 
1436
    /*
 
1437
      Substitute constants only in Item_rows. Don't affect other Items
 
1438
      with ROW_RESULT (eg Item_singlerow_subselect).
 
1439
 
 
1440
      For such Items more optimal is to detect if it is constant and replace
 
1441
      it with Item_row. This would optimize queries like this:
 
1442
      SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
 
1443
    */
 
1444
    Item_row *item_row= (Item_row*) item;
 
1445
    Item_row *comp_item_row= (Item_row*) comp_item;
 
1446
    uint32_t col;
 
1447
    new_item= 0;
 
1448
    /*
 
1449
      If item and comp_item are both Item_rows and have same number of cols
 
1450
      then process items in Item_row one by one.
 
1451
      We can't ignore NULL values here as this item may be used with <=>, in
 
1452
      which case NULL's are significant.
 
1453
    */
 
1454
    assert(item->result_type() == comp_item->result_type());
 
1455
    assert(item_row->cols() == comp_item_row->cols());
 
1456
    col= item_row->cols();
 
1457
    while (col-- > 0)
 
1458
      resolve_const_item(session, item_row->addr(col),
 
1459
                         comp_item_row->element_index(col));
 
1460
    break;
 
1461
  }
 
1462
  /* Fallthrough */
 
1463
  case REAL_RESULT:
 
1464
  {                                             // It must REAL_RESULT
 
1465
    double result= item->val_real();
 
1466
    uint32_t length=item->max_length,decimals=item->decimals;
 
1467
    bool null_value=item->null_value;
 
1468
    new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
 
1469
               new Item_float(name, result, decimals, length));
 
1470
    break;
 
1471
  }
 
1472
  case DECIMAL_RESULT:
 
1473
  {
 
1474
    my_decimal decimal_value;
 
1475
    my_decimal *result= item->val_decimal(&decimal_value);
 
1476
    uint32_t length= item->max_length, decimals= item->decimals;
 
1477
    bool null_value= item->null_value;
 
1478
    new_item= (null_value ?
 
1479
               (Item*) new Item_null(name) :
 
1480
               (Item*) new Item_decimal(name, result, length, decimals));
 
1481
    break;
 
1482
  }
 
1483
  default:
 
1484
    assert(0);
 
1485
  }
 
1486
  if (new_item)
 
1487
    session->change_item_tree(ref, new_item);
 
1488
}
 
1489
 
 
1490
bool field_is_equal_to_item(Field *field,Item *item)
 
1491
{
 
1492
 
 
1493
  Item_result res_type=item_cmp_type(field->result_type(),
 
1494
                                     item->result_type());
 
1495
  if (res_type == STRING_RESULT)
 
1496
  {
 
1497
    char item_buff[MAX_FIELD_WIDTH];
 
1498
    char field_buff[MAX_FIELD_WIDTH];
 
1499
    String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result;
 
1500
    String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
 
1501
    item_result=item->val_str(&item_tmp);
 
1502
    if (item->null_value)
 
1503
      return 1;                                 // This must be true
 
1504
    field->val_str(&field_tmp);
 
1505
    return !stringcmp(&field_tmp,item_result);
 
1506
  }
 
1507
  if (res_type == INT_RESULT)
 
1508
    return 1;                                   // Both where of type int
 
1509
  if (res_type == DECIMAL_RESULT)
 
1510
  {
 
1511
    my_decimal item_buf, *item_val,
 
1512
               field_buf, *field_val;
 
1513
    item_val= item->val_decimal(&item_buf);
 
1514
    if (item->null_value)
 
1515
      return 1;                                 // This must be true
 
1516
    field_val= field->val_decimal(&field_buf);
 
1517
    return !my_decimal_cmp(item_val, field_val);
 
1518
  }
 
1519
  double result= item->val_real();
 
1520
  if (item->null_value)
 
1521
    return 1;
 
1522
  return result == field->val_real();
 
1523
}
 
1524
 
 
1525
void dummy_error_processor(Session *, void *)
 
1526
{}
 
1527
 
 
1528
/**
 
1529
  Create field for temporary table using type of given item.
 
1530
 
 
1531
  @param session                   Thread handler
 
1532
  @param item                  Item to create a field for
 
1533
  @param table                 Temporary table
 
1534
  @param copy_func             If set and item is a function, store copy of
 
1535
                               item in this array
 
1536
  @param modify_item           1 if item->result_field should point to new
 
1537
                               item. This is relevent for how fill_record()
 
1538
                               is going to work:
 
1539
                               If modify_item is 1 then fill_record() will
 
1540
                               update the record in the original table.
 
1541
                               If modify_item is 0 then fill_record() will
 
1542
                               update the temporary table
 
1543
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
 
1544
                               field instead of blob.
 
1545
 
 
1546
  @retval
 
1547
    0  on error
 
1548
  @retval
 
1549
    new_created field
 
1550
*/
 
1551
static Field *create_tmp_field_from_item(Session *,
 
1552
                                         Item *item, Table *table,
 
1553
                                         Item ***copy_func, bool modify_item,
 
1554
                                         uint32_t convert_blob_length)
 
1555
{
 
1556
  bool maybe_null= item->maybe_null;
 
1557
  Field *new_field;
 
1558
 
 
1559
  switch (item->result_type()) {
 
1560
  case REAL_RESULT:
 
1561
    new_field= new Field_double(item->max_length, maybe_null,
 
1562
                                item->name, item->decimals, true);
 
1563
    break;
 
1564
  case INT_RESULT:
 
1565
    /*
 
1566
      Select an integer type with the minimal fit precision.
 
1567
      MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
 
1568
      Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into
 
1569
      Field_long : make them Field_int64_t.
 
1570
    */
 
1571
    if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
 
1572
      new_field=new Field_int64_t(item->max_length, maybe_null,
 
1573
                                   item->name, item->unsigned_flag);
 
1574
    else
 
1575
      new_field=new Field_long(item->max_length, maybe_null,
 
1576
                               item->name, item->unsigned_flag);
 
1577
    break;
 
1578
  case STRING_RESULT:
 
1579
    assert(item->collation.collation);
 
1580
 
 
1581
    enum enum_field_types type;
 
1582
    /*
 
1583
      DATE/TIME fields have STRING_RESULT result type.
 
1584
      To preserve type they needed to be handled separately.
 
1585
    */
 
1586
    if ((type= item->field_type()) == DRIZZLE_TYPE_DATETIME ||
 
1587
        type == DRIZZLE_TYPE_DATE ||
 
1588
        type == DRIZZLE_TYPE_TIMESTAMP)
 
1589
      new_field= item->tmp_table_field_from_field_type(table, 1);
 
1590
    /*
 
1591
      Make sure that the blob fits into a Field_varstring which has
 
1592
      2-byte lenght.
 
1593
    */
 
1594
    else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
 
1595
             convert_blob_length <= Field_varstring::MAX_SIZE &&
 
1596
             convert_blob_length)
 
1597
      new_field= new Field_varstring(convert_blob_length, maybe_null,
 
1598
                                     item->name, table->s,
 
1599
                                     item->collation.collation);
 
1600
    else
 
1601
      new_field= item->make_string_field(table);
 
1602
    new_field->set_derivation(item->collation.derivation);
 
1603
    break;
 
1604
  case DECIMAL_RESULT:
 
1605
  {
 
1606
    uint8_t dec= item->decimals;
 
1607
    uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
 
1608
    uint32_t len= item->max_length;
 
1609
 
 
1610
    /*
 
1611
      Trying to put too many digits overall in a DECIMAL(prec,dec)
 
1612
      will always throw a warning. We must limit dec to
 
1613
      DECIMAL_MAX_SCALE however to prevent an assert() later.
 
1614
    */
 
1615
 
 
1616
    if (dec > 0)
 
1617
    {
 
1618
      signed int overflow;
 
1619
 
 
1620
      dec= min(dec, (uint8_t)DECIMAL_MAX_SCALE);
 
1621
 
 
1622
      /*
 
1623
        If the value still overflows the field with the corrected dec,
 
1624
        we'll throw out decimals rather than integers. This is still
 
1625
        bad and of course throws a truncation warning.
 
1626
        +1: for decimal point
 
1627
      */
 
1628
 
 
1629
      overflow= my_decimal_precision_to_length(intg + dec, dec,
 
1630
                                               item->unsigned_flag) - len;
 
1631
 
 
1632
      if (overflow > 0)
 
1633
        dec= max(0, dec - overflow);            // too long, discard fract
 
1634
      else
 
1635
        len-= item->decimals - dec;             // corrected value fits
 
1636
    }
 
1637
 
 
1638
    new_field= new Field_decimal(len,
 
1639
                                 maybe_null,
 
1640
                                 item->name,
 
1641
                                 dec,
 
1642
                                 item->unsigned_flag);
 
1643
    break;
 
1644
  }
 
1645
  case ROW_RESULT:
 
1646
  default:
 
1647
    // This case should never be choosen
 
1648
    assert(0);
 
1649
    new_field= 0;
 
1650
    break;
 
1651
  }
 
1652
  if (new_field)
 
1653
    new_field->init(table);
 
1654
 
 
1655
  if (copy_func && item->is_result_field())
 
1656
    *((*copy_func)++) = item;                   // Save for copy_funcs
 
1657
  if (modify_item)
 
1658
    item->set_result_field(new_field);
 
1659
  if (item->type() == Item::NULL_ITEM)
 
1660
    new_field->is_created_from_null_item= true;
 
1661
  return new_field;
 
1662
}
 
1663
 
 
1664
Field *create_tmp_field(Session *session,
 
1665
                        Table *table,
 
1666
                        Item *item,
 
1667
                        Item::Type type,
 
1668
                        Item ***copy_func,
 
1669
                        Field **from_field,
 
1670
                        Field **default_field,
 
1671
                        bool group,
 
1672
                        bool modify_item,
 
1673
                        bool make_copy_field,
 
1674
                        uint32_t convert_blob_length)
 
1675
{
 
1676
  Field *result;
 
1677
  Item::Type orig_type= type;
 
1678
  Item *orig_item= 0;
 
1679
 
 
1680
  if (type != Item::FIELD_ITEM &&
 
1681
      item->real_item()->type() == Item::FIELD_ITEM)
 
1682
  {
 
1683
    orig_item= item;
 
1684
    item= item->real_item();
 
1685
    type= Item::FIELD_ITEM;
 
1686
  }
 
1687
 
 
1688
  switch (type) {
 
1689
  case Item::SUM_FUNC_ITEM:
 
1690
  {
 
1691
    Item_sum *item_sum=(Item_sum*) item;
 
1692
    result= item_sum->create_tmp_field(group, table, convert_blob_length);
 
1693
    if (!result)
 
1694
      my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
 
1695
    return result;
 
1696
  }
 
1697
  case Item::FIELD_ITEM:
 
1698
  case Item::DEFAULT_VALUE_ITEM:
 
1699
  {
 
1700
    Item_field *field= (Item_field*) item;
 
1701
    bool orig_modify= modify_item;
 
1702
    if (orig_type == Item::REF_ITEM)
 
1703
      modify_item= 0;
 
1704
    /*
 
1705
      If item have to be able to store NULLs but underlaid field can't do it,
 
1706
      create_tmp_field_from_field() can't be used for tmp field creation.
 
1707
    */
 
1708
    if (field->maybe_null && !field->field->maybe_null())
 
1709
    {
 
1710
      result= create_tmp_field_from_item(session, item, table, NULL,
 
1711
                                         modify_item, convert_blob_length);
 
1712
      *from_field= field->field;
 
1713
      if (result && modify_item)
 
1714
        field->result_field= result;
 
1715
    }
 
1716
    else
 
1717
      result= create_tmp_field_from_field(session, (*from_field= field->field),
 
1718
                                          orig_item ? orig_item->name :
 
1719
                                          item->name,
 
1720
                                          table,
 
1721
                                          modify_item ? field :
 
1722
                                          NULL,
 
1723
                                          convert_blob_length);
 
1724
    if (orig_type == Item::REF_ITEM && orig_modify)
 
1725
      ((Item_ref*)orig_item)->set_result_field(result);
 
1726
    if (field->field->eq_def(result))
 
1727
      *default_field= field->field;
 
1728
    return result;
 
1729
  }
 
1730
  /* Fall through */
 
1731
  case Item::FUNC_ITEM:
 
1732
    /* Fall through */
 
1733
  case Item::COND_ITEM:
 
1734
  case Item::FIELD_AVG_ITEM:
 
1735
  case Item::FIELD_STD_ITEM:
 
1736
  case Item::SUBSELECT_ITEM:
 
1737
    /* The following can only happen with 'CREATE TABLE ... SELECT' */
 
1738
  case Item::PROC_ITEM:
 
1739
  case Item::INT_ITEM:
 
1740
  case Item::REAL_ITEM:
 
1741
  case Item::DECIMAL_ITEM:
 
1742
  case Item::STRING_ITEM:
 
1743
  case Item::REF_ITEM:
 
1744
  case Item::NULL_ITEM:
 
1745
  case Item::VARBIN_ITEM:
 
1746
    if (make_copy_field)
 
1747
    {
 
1748
      assert(((Item_result_field*)item)->result_field);
 
1749
      *from_field= ((Item_result_field*)item)->result_field;
 
1750
    }
 
1751
    return create_tmp_field_from_item(session, item, table,
 
1752
                                      (make_copy_field ? 0 : copy_func),
 
1753
                                       modify_item, convert_blob_length);
 
1754
  case Item::TYPE_HOLDER:
 
1755
    result= ((Item_type_holder *)item)->make_field_by_type(table);
 
1756
    result->set_derivation(item->collation.derivation);
 
1757
    return result;
 
1758
  default:                                      // Dosen't have to be stored
 
1759
    return NULL;
 
1760
  }
 
1761
}
 
1762
 
 
1763
} /* namespace drizzled */