~drizzle-trunk/drizzle/development

584.4.5 by Monty Taylor
Split out cache_row and type_holder.
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 *
4
 *  Copyright (C) 2008 Sun Microsystems
5
 *
6
 *  This program is free software; you can redistribute it and/or modify
7
 *  it under the terms of the GNU General Public License as published by
8
 *  the Free Software Foundation; version 2 of the License.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, write to the Free Software
17
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
 */
1 by brian
clean slate
19
20
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
21
#include <drizzled/server_includes.h>
575.4.7 by Monty Taylor
More header cleanup.
22
#include CMATH_H
23
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
24
#include <drizzled/sql_select.h>
549 by Monty Taylor
Took gettext.h out of header files.
25
#include <drizzled/error.h>
575.4.7 by Monty Taylor
More header cleanup.
26
#include <drizzled/show.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
27
#include <drizzled/item/cmpfunc.h>
584.4.5 by Monty Taylor
Split out cache_row and type_holder.
28
#include <drizzled/item/cache_row.h>
29
#include <drizzled/item/type_holder.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
30
#include <drizzled/item/sum.h>
31
#include <drizzled/functions/str/conv_charset.h>
584.1.13 by Monty Taylor
Split out a little more code. Removed table_list.h from common_includes.
32
#include <drizzled/virtual_column_info.h>
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
33
#include <drizzled/sql_base.h>
572.1.4 by Monty Taylor
Removed a bunch of unusued tests and defines from autoconf.
34
584.5.1 by Monty Taylor
Removed field includes from field.h.
35
36
#include <drizzled/field/str.h>
37
#include <drizzled/field/longstr.h>
38
#include <drizzled/field/num.h>
39
#include <drizzled/field/blob.h>
40
#include <drizzled/field/enum.h>
41
#include <drizzled/field/null.h>
42
#include <drizzled/field/date.h>
670.1.1 by Monty Taylor
Renamed fdecimal.* to decimal.*. Let's see how many things we can break!
43
#include <drizzled/field/decimal.h>
584.5.1 by Monty Taylor
Removed field includes from field.h.
44
#include <drizzled/field/real.h>
45
#include <drizzled/field/double.h>
46
#include <drizzled/field/long.h>
47
#include <drizzled/field/int64_t.h>
48
#include <drizzled/field/num.h>
49
#include <drizzled/field/timetype.h>
50
#include <drizzled/field/timestamp.h>
51
#include <drizzled/field/datetime.h>
52
#include <drizzled/field/varstring.h>
53
54
572.1.4 by Monty Taylor
Removed a bunch of unusued tests and defines from autoconf.
55
#if defined(CMATH_NAMESPACE)
56
using namespace CMATH_NAMESPACE;
57
#endif
1 by brian
clean slate
58
59
const String my_null_string("NULL", 4, default_charset_info);
60
61
/*****************************************************************************
62
** Item functions
63
*****************************************************************************/
64
65
/**
66
  Init all special items.
67
*/
68
69
void item_init(void)
70
{
71
}
72
73
584.4.8 by Monty Taylor
Moved stuff from item.h to item.cc
74
bool Item::is_expensive_processor(unsigned char *)
75
{
76
  return 0;
77
}
78
79
void Item::fix_after_pullout(st_select_lex *, Item **)
80
{}
81
82
83
Field *Item::tmp_table_field(Table *)
84
{
85
  return 0;
86
}
87
88
89
const char *Item::full_name(void) const
90
{
91
  return name ? name : "???";
92
}
93
94
95
int64_t Item::val_int_endpoint(bool, bool *)
96
{
97
  assert(0);
98
  return 0;
99
}
100
101
1 by brian
clean slate
102
/**
103
  @todo
104
    Make this functions class dependent
105
*/
106
107
bool Item::val_bool()
108
{
109
  switch(result_type()) {
110
  case INT_RESULT:
111
    return val_int() != 0;
112
  case DECIMAL_RESULT:
113
  {
114
    my_decimal decimal_value;
115
    my_decimal *val= val_decimal(&decimal_value);
116
    if (val)
117
      return !my_decimal_is_zero(val);
118
    return 0;
119
  }
120
  case REAL_RESULT:
121
  case STRING_RESULT:
122
    return val_real() != 0.0;
123
  case ROW_RESULT:
124
  default:
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
125
    assert(0);
1 by brian
clean slate
126
    return 0;                                   // Wrong (but safe)
127
  }
128
}
129
130
131
String *Item::val_string_from_real(String *str)
132
{
133
  double nr= val_real();
134
  if (null_value)
135
    return 0;					/* purecov: inspected */
136
  str->set_real(nr,decimals, &my_charset_bin);
137
  return str;
138
}
139
140
141
String *Item::val_string_from_int(String *str)
142
{
152 by Brian Aker
longlong replacement
143
  int64_t nr= val_int();
1 by brian
clean slate
144
  if (null_value)
145
    return 0;
146
  str->set_int(nr, unsigned_flag, &my_charset_bin);
147
  return str;
148
}
149
150
151
String *Item::val_string_from_decimal(String *str)
152
{
153
  my_decimal dec_buf, *dec= val_decimal(&dec_buf);
154
  if (null_value)
155
    return 0;
56 by brian
Next pass of true/false update.
156
  my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, false, &dec_buf);
1 by brian
clean slate
157
  my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
158
  return str;
159
}
160
161
162
my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
163
{
164
  double nr= val_real();
165
  if (null_value)
166
    return 0;
167
  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
168
  return (decimal_value);
169
}
170
171
172
my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
173
{
152 by Brian Aker
longlong replacement
174
  int64_t nr= val_int();
1 by brian
clean slate
175
  if (null_value)
176
    return 0;
177
  int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
178
  return decimal_value;
179
}
180
181
182
my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
183
{
184
  String *res;
185
  char *end_ptr;
186
  if (!(res= val_str(&str_value)))
187
    return 0;                                   // NULL or EOM
188
189
  end_ptr= (char*) res->ptr()+ res->length();
190
  if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
191
                     res->ptr(), res->length(), res->charset(),
192
                     decimal_value) & E_DEC_BAD_NUM)
193
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
194
    push_warning_printf(current_session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
195
                        ER_TRUNCATED_WRONG_VALUE,
196
                        ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
197
                        str_value.c_ptr());
198
  }
199
  return decimal_value;
200
}
201
202
203
my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value)
204
{
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
205
  assert(fixed == 1);
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
206
  DRIZZLE_TIME ltime;
1 by brian
clean slate
207
  if (get_date(&ltime, TIME_FUZZY_DATE))
208
  {
209
    my_decimal_set_zero(decimal_value);
210
    null_value= 1;                               // set NULL, stop processing
211
    return 0;
212
  }
213
  return date2my_decimal(&ltime, decimal_value);
214
}
215
216
217
my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value)
218
{
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
219
  assert(fixed == 1);
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
220
  DRIZZLE_TIME ltime;
1 by brian
clean slate
221
  if (get_time(&ltime))
222
  {
223
    my_decimal_set_zero(decimal_value);
224
    return 0;
225
  }
226
  return date2my_decimal(&ltime, decimal_value);
227
}
228
229
230
double Item::val_real_from_decimal()
231
{
232
  /* Note that fix_fields may not be called for Item_avg_field items */
233
  double result;
234
  my_decimal value_buff, *dec_val= val_decimal(&value_buff);
235
  if (null_value)
236
    return 0.0;
237
  my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
238
  return result;
239
}
240
241
152 by Brian Aker
longlong replacement
242
int64_t Item::val_int_from_decimal()
1 by brian
clean slate
243
{
244
  /* Note that fix_fields may not be called for Item_avg_field items */
152 by Brian Aker
longlong replacement
245
  int64_t result;
1 by brian
clean slate
246
  my_decimal value, *dec_val= val_decimal(&value);
247
  if (null_value)
248
    return 0;
249
  my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result);
250
  return result;
251
}
252
253
int Item::save_time_in_field(Field *field)
254
{
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
255
  DRIZZLE_TIME ltime;
1 by brian
clean slate
256
  if (get_time(&ltime))
257
    return set_field_to_null(field);
258
  field->set_notnull();
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
259
  return field->store_time(&ltime, DRIZZLE_TIMESTAMP_TIME);
1 by brian
clean slate
260
}
261
262
263
int Item::save_date_in_field(Field *field)
264
{
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
265
  DRIZZLE_TIME ltime;
1 by brian
clean slate
266
  if (get_date(&ltime, TIME_FUZZY_DATE))
267
    return set_field_to_null(field);
268
  field->set_notnull();
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
269
  return field->store_time(&ltime, DRIZZLE_TIMESTAMP_DATETIME);
1 by brian
clean slate
270
}
271
272
273
/*
274
  Store the string value in field directly
275
276
  SYNOPSIS
277
    Item::save_str_value_in_field()
278
    field   a pointer to field where to store
279
    result  the pointer to the string value to be stored
280
281
  DESCRIPTION
282
    The method is used by Item_*::save_in_field implementations
283
    when we don't need to calculate the value to store
284
    See Item_string::save_in_field() implementation for example
285
286
  IMPLEMENTATION
287
    Check if the Item is null and stores the NULL or the
288
    result value in the field accordingly.
289
290
  RETURN
291
    Nonzero value if error
292
*/
293
294
int Item::save_str_value_in_field(Field *field, String *result)
295
{
296
  if (null_value)
297
    return set_field_to_null(field);
298
  field->set_notnull();
299
  return field->store(result->ptr(), result->length(),
300
		      collation.collation);
301
}
302
303
304
Item::Item():
650 by Brian Aker
Removing the SP bits.
305
  is_expensive_cache(-1), name(0), orig_name(0), name_length(0),
56 by brian
Next pass of true/false update.
306
  fixed(0), is_autogenerated_name(true),
1 by brian
clean slate
307
  collation(&my_charset_bin, DERIVATION_COERCIBLE)
308
{
309
  marker= 0;
275 by Brian Aker
Full removal of my_bool from central server.
310
  maybe_null= false;
311
  null_value= false;
312
  with_sum_func= false;
313
  unsigned_flag= false;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
314
  decimals= 0;
275 by Brian Aker
Full removal of my_bool from central server.
315
  max_length= 0;
1 by brian
clean slate
316
  with_subselect= 0;
317
  cmp_context= (Item_result)-1;
318
319
  /* Put item in free list so that we can free all items at end */
520.1.22 by Brian Aker
Second pass of thd cleanup
320
  Session *session= current_session;
321
  next= session->free_list;
322
  session->free_list= this;
1 by brian
clean slate
323
  /*
324
    Item constructor can be called during execution other then SQL_COM
520.1.22 by Brian Aker
Second pass of thd cleanup
325
    command => we should check session->lex->current_select on zero (session->lex
1 by brian
clean slate
326
    can be uninitialised)
327
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
328
  if (session->lex->current_select)
1 by brian
clean slate
329
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
330
    enum_parsing_place place=
520.1.22 by Brian Aker
Second pass of thd cleanup
331
      session->lex->current_select->parsing_place;
1 by brian
clean slate
332
    if (place == SELECT_LIST ||
333
	place == IN_HAVING)
520.1.22 by Brian Aker
Second pass of thd cleanup
334
      session->lex->current_select->select_n_having_items++;
1 by brian
clean slate
335
  }
336
}
337
338
/**
339
  Constructor used by Item_field, Item_ref & aggregate (sum)
340
  functions.
341
342
  Used for duplicating lists in processing queries with temporary
343
  tables.
344
*/
520.1.22 by Brian Aker
Second pass of thd cleanup
345
Item::Item(Session *session, Item *item):
1 by brian
clean slate
346
  is_expensive_cache(-1),
347
  str_value(item->str_value),
348
  name(item->name),
349
  orig_name(item->orig_name),
350
  max_length(item->max_length),
351
  marker(item->marker),
352
  decimals(item->decimals),
353
  maybe_null(item->maybe_null),
354
  null_value(item->null_value),
355
  unsigned_flag(item->unsigned_flag),
356
  with_sum_func(item->with_sum_func),
357
  fixed(item->fixed),
358
  collation(item->collation),
359
  cmp_context(item->cmp_context)
360
{
520.1.22 by Brian Aker
Second pass of thd cleanup
361
  next= session->free_list;				// Put in free list
362
  session->free_list= this;
1 by brian
clean slate
363
}
364
365
482 by Brian Aker
Remove uint.
366
uint32_t Item::decimal_precision() const
1 by brian
clean slate
367
{
368
  Item_result restype= result_type();
369
370
  if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
398.1.4 by Monty Taylor
Renamed max/min.
371
    return cmin(my_decimal_length_to_precision(max_length, decimals, unsigned_flag),
287.3.8 by Monty Taylor
Oy. Replaced max and min macros with std::max and std::min so that we get
372
               (unsigned int)DECIMAL_MAX_PRECISION);
398.1.4 by Monty Taylor
Renamed max/min.
373
  return cmin(max_length, (uint32_t)DECIMAL_MAX_PRECISION);
1 by brian
clean slate
374
}
375
376
584.1.14 by Monty Taylor
Removed field.h from common_includes.
377
int Item::decimal_int_part() const
378
{
379
  return my_decimal_int_part(decimal_precision(), decimals);
380
}
381
382
584.4.8 by Monty Taylor
Moved stuff from item.h to item.cc
383
void Item::print(String *str, enum_query_type)
384
{
385
  str->append(full_name());
386
}
387
388
1 by brian
clean slate
389
void Item::print_item_w_name(String *str, enum_query_type query_type)
390
{
391
  print(str, query_type);
392
393
  if (name)
394
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
395
    Session *session= current_session;
1 by brian
clean slate
396
    str->append(STRING_WITH_LEN(" AS "));
520.1.22 by Brian Aker
Second pass of thd cleanup
397
    append_identifier(session, str, name, (uint) strlen(name));
1 by brian
clean slate
398
  }
399
}
400
401
584.4.8 by Monty Taylor
Moved stuff from item.h to item.cc
402
void Item::split_sum_func(Session *, Item **, List<Item> &)
403
{}
404
405
1 by brian
clean slate
406
void Item::cleanup()
407
{
408
  fixed=0;
409
  marker= 0;
410
  if (orig_name)
411
    name= orig_name;
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
412
  return;
1 by brian
clean slate
413
}
414
415
416
/**
417
  cleanup() item if it is 'fixed'.
418
419
  @param arg   a dummy parameter, is not used here
420
*/
421
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
422
bool Item::cleanup_processor(unsigned char *)
1 by brian
clean slate
423
{
424
  if (fixed)
425
    cleanup();
56 by brian
Next pass of true/false update.
426
  return false;
1 by brian
clean slate
427
}
428
429
430
/**
431
  rename item (used for views, cleanup() return original name).
432
433
  @param new_name	new name of item;
434
*/
435
436
void Item::rename(char *new_name)
437
{
438
  /*
439
    we can compare pointers to names here, because if name was not changed,
440
    pointer will be same
441
  */
442
  if (!orig_name && new_name != name)
443
    orig_name= name;
444
  name= new_name;
445
}
446
447
448
/**
449
  Traverse item tree possibly transforming it (replacing items).
450
451
  This function is designed to ease transformation of Item trees.
452
  Re-execution note: every such transformation is registered for
520.1.21 by Brian Aker
THD -> Session rename
453
  rollback by Session::change_item_tree() and is rolled back at the end
454
  of execution by Session::rollback_item_tree_changes().
1 by brian
clean slate
455
456
  Therefore:
457
  - this function can not be used at prepared statement prepare
458
  (in particular, in fix_fields!), as only permanent
459
  transformation of Item trees are allowed at prepare.
460
  - the transformer function shall allocate new Items in execution
520.1.22 by Brian Aker
Second pass of thd cleanup
461
  memory root (session->mem_root) and not anywhere else: allocated
1 by brian
clean slate
462
  items will be gone in the end of execution.
463
464
  If you don't need to transform an item tree, but only traverse
465
  it, please use Item::walk() instead.
466
467
468
  @param transformer    functor that performs transformation of a subtree
469
  @param arg            opaque argument passed to the functor
470
471
  @return
520.1.21 by Brian Aker
THD -> Session rename
472
    Returns pointer to the new subtree root.  Session::change_item_tree()
1 by brian
clean slate
473
    should be called for it if transformation took place, i.e. if a
474
    pointer to newly allocated item is returned.
475
*/
476
481 by Brian Aker
Remove all of uchar.
477
Item* Item::transform(Item_transformer transformer, unsigned char *arg)
1 by brian
clean slate
478
{
479
  return (this->*transformer)(arg);
480
}
481
482
482 by Brian Aker
Remove uint.
483
bool Item::check_cols(uint32_t c)
1 by brian
clean slate
484
{
485
  if (c != 1)
486
  {
487
    my_error(ER_OPERAND_COLUMNS, MYF(0), c);
488
    return 1;
489
  }
490
  return 0;
491
}
492
493
482 by Brian Aker
Remove uint.
494
void Item::set_name(const char *str, uint32_t length, const CHARSET_INFO * const cs)
1 by brian
clean slate
495
{
496
  if (!length)
497
  {
498
    /* Empty string, used by AS or internal function like last_insert_id() */
499
    name= (char*) str;
500
    name_length= 0;
501
    return;
502
  }
503
  if (cs->ctype)
504
  {
482 by Brian Aker
Remove uint.
505
    uint32_t orig_len= length;
1 by brian
clean slate
506
    /*
507
      This will probably need a better implementation in the future:
508
      a function in CHARSET_INFO structure.
509
    */
510
    while (length && !my_isgraph(cs,*str))
511
    {						// Fix problem with yacc
512
      length--;
513
      str++;
514
    }
515
    if (orig_len != length && !is_autogenerated_name)
516
    {
517
      if (length == 0)
520.1.22 by Brian Aker
Second pass of thd cleanup
518
        push_warning_printf(current_session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
519
                            ER_NAME_BECOMES_EMPTY, ER(ER_NAME_BECOMES_EMPTY),
520
                            str + length - orig_len);
521
      else
520.1.22 by Brian Aker
Second pass of thd cleanup
522
        push_warning_printf(current_session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
523
                            ER_REMOVED_SPACES, ER(ER_REMOVED_SPACES),
524
                            str + length - orig_len);
525
    }
526
  }
527
  if (!my_charset_same(cs, system_charset_info))
528
  {
529
    size_t res_length;
530
    name= sql_strmake_with_convert(str, name_length= length, cs,
531
				   MAX_ALIAS_NAME, system_charset_info,
532
				   &res_length);
533
  }
534
  else
398.1.4 by Monty Taylor
Renamed max/min.
535
    name= sql_strmake(str, (name_length= cmin(length,(unsigned int)MAX_ALIAS_NAME)));
1 by brian
clean slate
536
}
537
538
539
/**
540
  @details
541
  This function is called when:
542
  - Comparing items in the WHERE clause (when doing where optimization)
327.2.3 by Brian Aker
Refactoring of class Table
543
  - When trying to find an order_st BY/GROUP BY item in the SELECT part
1 by brian
clean slate
544
*/
545
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
546
bool Item::eq(const Item *item, bool) const
1 by brian
clean slate
547
{
548
  /*
56 by brian
Next pass of true/false update.
549
    Note, that this is never true if item is a Item_param:
1 by brian
clean slate
550
    for all basic constants we have special checks, and Item_param's
551
    type() can be only among basic constant types.
552
  */
553
  return type() == item->type() && name && item->name &&
554
    !my_strcasecmp(system_charset_info,name,item->name);
555
}
556
557
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
558
Item *Item::safe_charset_converter(const CHARSET_INFO * const tocs)
1 by brian
clean slate
559
{
560
  Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1);
561
  return conv->safe ? conv : NULL;
562
}
563
564
565
/**
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
566
  Get the value of the function as a DRIZZLE_TIME structure.
1 by brian
clean slate
567
  As a extra convenience the time structure is reset on error!
568
*/
569
482 by Brian Aker
Remove uint.
570
bool Item::get_date(DRIZZLE_TIME *ltime,uint32_t fuzzydate)
1 by brian
clean slate
571
{
572
  if (result_type() == STRING_RESULT)
573
  {
574
    char buff[40];
575
    String tmp(buff,sizeof(buff), &my_charset_bin),*res;
576
    if (!(res=val_str(&tmp)) ||
577
        str_to_datetime_with_warn(res->ptr(), res->length(),
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
578
                                  ltime, fuzzydate) <= DRIZZLE_TIMESTAMP_ERROR)
1 by brian
clean slate
579
      goto err;
580
  }
581
  else
582
  {
152 by Brian Aker
longlong replacement
583
    int64_t value= val_int();
1 by brian
clean slate
584
    int was_cut;
398.1.8 by Monty Taylor
Enabled -Wlong-long.
585
    if (number_to_datetime(value, ltime, fuzzydate, &was_cut) == -1L)
1 by brian
clean slate
586
    {
587
      char buff[22], *end;
152 by Brian Aker
longlong replacement
588
      end= int64_t10_to_str(value, buff, -10);
520.1.22 by Brian Aker
Second pass of thd cleanup
589
      make_truncated_value_warning(current_session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
590
                                   buff, (int) (end-buff), DRIZZLE_TIMESTAMP_NONE,
461 by Monty Taylor
Removed NullS. bu-bye.
591
                                   NULL);
1 by brian
clean slate
592
      goto err;
593
    }
594
  }
595
  return 0;
596
597
err:
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
598
  memset(ltime, 0, sizeof(*ltime));
1 by brian
clean slate
599
  return 1;
600
}
601
602
/**
603
  Get time of first argument.\
604
605
  As a extra convenience the time structure is reset on error!
606
*/
607
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
608
bool Item::get_time(DRIZZLE_TIME *ltime)
1 by brian
clean slate
609
{
610
  char buff[40];
611
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
612
  if (!(res=val_str(&tmp)) ||
613
      str_to_time_with_warn(res->ptr(), res->length(), ltime))
614
  {
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
615
    memset(ltime, 0, sizeof(*ltime));
584.4.8 by Monty Taylor
Moved stuff from item.h to item.cc
616
    return true;
1 by brian
clean slate
617
  }
584.4.8 by Monty Taylor
Moved stuff from item.h to item.cc
618
  return false;
619
}
620
621
622
bool Item::get_date_result(DRIZZLE_TIME *ltime,uint32_t fuzzydate)
623
{
624
  return get_date(ltime,fuzzydate);
625
}
626
627
628
bool Item::is_null()
629
{
630
  return false;
631
}
632
633
634
void Item::update_null_value ()
635
{
636
  (void) val_int();
637
}
638
639
640
void Item::top_level_item(void)
641
{}
642
643
644
void Item::set_result_field(Field *)
645
{}
646
647
648
bool Item::is_result_field(void)
649
{
650
  return 0;
651
}
652
653
654
bool Item::is_bool_func(void)
655
{
656
  return 0;
657
}
658
659
660
void Item::save_in_result_field(bool)
661
{}
662
663
664
void Item::no_rows_in_result(void)
665
{}
666
667
668
Item *Item::copy_or_same(Session *)
669
{
670
  return this;
671
}
672
673
674
Item *Item::copy_andor_structure(Session *)
675
{
676
  return this;
677
}
678
679
680
Item *Item::real_item(void)
681
{
682
  return this;
683
}
684
685
686
Item *Item::get_tmp_table_item(Session *session)
687
{
688
  return copy_or_same(session);
689
}
690
1 by brian
clean slate
691
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
692
const CHARSET_INFO *Item::default_charset()
1 by brian
clean slate
693
{
520.1.22 by Brian Aker
Second pass of thd cleanup
694
  return current_session->variables.collation_connection;
1 by brian
clean slate
695
}
696
697
584.4.8 by Monty Taylor
Moved stuff from item.h to item.cc
698
const CHARSET_INFO *Item::compare_collation()
699
{
700
  return NULL;
701
}
702
703
704
bool Item::walk(Item_processor processor, bool, unsigned char *arg)
705
{
706
  return (this->*processor)(arg);
707
}
708
709
710
Item* Item::compile(Item_analyzer analyzer, unsigned char **arg_p,
711
                    Item_transformer transformer, unsigned char *arg_t)
712
{
713
  if ((this->*analyzer) (arg_p))
714
    return ((this->*transformer) (arg_t));
715
  return 0;
716
}
717
718
719
void Item::traverse_cond(Cond_traverser traverser, void *arg, traverse_order)
720
{
721
  (*traverser)(this, arg);
722
}
723
724
725
bool Item::remove_dependence_processor(unsigned char *)
726
{
727
  return 0;
728
}
729
730
731
bool Item::remove_fixed(unsigned char *)
732
{
733
  fixed= 0;
734
  return 0;
735
}
736
737
738
bool Item::collect_item_field_processor(unsigned char *)
739
{
740
  return 0;
741
}
742
743
744
bool Item::find_item_in_field_list_processor(unsigned char *)
745
{
746
  return 0;
747
}
748
749
750
bool Item::change_context_processor(unsigned char *)
751
{
752
  return 0;
753
}
754
755
bool Item::reset_query_id_processor(unsigned char *)
756
{
757
  return 0;
758
}
759
760
761
bool Item::register_field_in_read_map(unsigned char *)
762
{
763
  return 0;
764
}
765
766
767
bool Item::register_field_in_bitmap(unsigned char *)
768
{
769
  return 0;
770
}
771
772
773
bool Item::subst_argument_checker(unsigned char **arg)
774
{
775
  if (*arg)
776
    *arg= NULL;
777
  return true;
778
}
779
780
781
bool Item::check_vcol_func_processor(unsigned char *)
782
{
783
  return true;
784
}
785
786
787
Item *Item::equal_fields_propagator(unsigned char *)
788
{
789
  return this;
790
}
791
792
793
bool Item::set_no_const_sub(unsigned char *)
794
{
795
  return false;
796
}
797
798
799
Item *Item::replace_equal_field(unsigned char *)
800
{
801
  return this;
802
}
803
804
805
uint32_t Item::cols()
806
{
807
  return 1;
808
}
809
810
811
Item* Item::element_index(uint32_t)
812
{
813
  return this;
814
}
815
816
817
Item** Item::addr(uint32_t)
818
{
819
  return 0;
820
}
821
822
823
bool Item::null_inside()
824
{
825
  return 0;
826
}
827
828
829
void Item::bring_value()
830
{}
831
832
833
Item *Item::neg_transformer(Session *)
834
{
835
  return NULL;
836
}
837
838
839
Item *Item::update_value_transformer(unsigned char *)
840
{
841
  return this;
842
}
843
844
845
void Item::delete_self()
846
{
847
  cleanup();
848
  delete this;
849
}
850
851
bool Item::result_as_int64_t()
852
{
853
  return false;
854
}
855
856
857
bool Item::is_expensive()
858
{
859
  if (is_expensive_cache < 0)
860
    is_expensive_cache= walk(&Item::is_expensive_processor, 0,
861
                             (unsigned char*)0);
862
  return test(is_expensive_cache);
863
}
864
1 by brian
clean slate
865
866
int Item::save_in_field_no_warnings(Field *field, bool no_conversions)
867
{
868
  int res;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
869
  Table *table= field->table;
520.1.22 by Brian Aker
Second pass of thd cleanup
870
  Session *session= table->in_use;
871
  enum_check_fields tmp= session->count_cuted_fields;
872
  ulong sql_mode= session->variables.sql_mode;
873
  session->variables.sql_mode&= ~(MODE_NO_ZERO_DATE);
874
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1 by brian
clean slate
875
  res= save_in_field(field, no_conversions);
520.1.22 by Brian Aker
Second pass of thd cleanup
876
  session->count_cuted_fields= tmp;
877
  session->variables.sql_mode= sql_mode;
1 by brian
clean slate
878
  return res;
879
}
880
881
882
/*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
883
 need a special class to adjust printing : references to aggregate functions
1 by brian
clean slate
884
 must not be printed as refs because the aggregate functions that are added to
885
 the front of select list are not printed as well.
886
*/
887
class Item_aggregate_ref : public Item_ref
888
{
889
public:
890
  Item_aggregate_ref(Name_resolution_context *context_arg, Item **item,
891
                  const char *table_name_arg, const char *field_name_arg)
892
    :Item_ref(context_arg, item, table_name_arg, field_name_arg) {}
893
894
  virtual inline void print (String *str, enum_query_type query_type)
895
  {
896
    if (ref)
897
      (*ref)->print(str, query_type);
898
    else
899
      Item_ident::print(str, query_type);
900
  }
901
};
902
903
904
/**
905
  Move SUM items out from item tree and replace with reference.
906
520.1.22 by Brian Aker
Second pass of thd cleanup
907
  @param session			Thread handler
1 by brian
clean slate
908
  @param ref_pointer_array	Pointer to array of reference fields
909
  @param fields		All fields in select
910
  @param ref			Pointer to item
911
  @param skip_registered       <=> function be must skipped for registered
912
                               SUM items
913
914
  @note
584.4.9 by Monty Taylor
Renamed split_sum_func2 to split_sum_func. It's C++.
915
    This is from split_sum_func() for items that should be split
1 by brian
clean slate
916
917
    All found SUM items are added FIRST in the fields list and
918
    we replace the item with a reference.
919
520.1.22 by Brian Aker
Second pass of thd cleanup
920
    session->fatal_error() may be called if we are out of memory
1 by brian
clean slate
921
*/
922
584.4.9 by Monty Taylor
Renamed split_sum_func2 to split_sum_func. It's C++.
923
void Item::split_sum_func(Session *session, Item **ref_pointer_array,
924
                          List<Item> &fields, Item **ref,
925
                          bool skip_registered)
1 by brian
clean slate
926
{
584.4.9 by Monty Taylor
Renamed split_sum_func2 to split_sum_func. It's C++.
927
  /* An item of type Item_sum  is registered <=> ref_by != 0 */
928
  if (type() == SUM_FUNC_ITEM && skip_registered &&
1 by brian
clean slate
929
      ((Item_sum *) this)->ref_by)
584.4.9 by Monty Taylor
Renamed split_sum_func2 to split_sum_func. It's C++.
930
    return;
1 by brian
clean slate
931
  if ((type() != SUM_FUNC_ITEM && with_sum_func) ||
932
      (type() == FUNC_ITEM &&
933
       (((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC ||
934
        ((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC)))
935
  {
936
    /* Will split complicated items and ignore simple ones */
520.1.22 by Brian Aker
Second pass of thd cleanup
937
    split_sum_func(session, ref_pointer_array, fields);
1 by brian
clean slate
938
  }
939
  else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) &&
940
           type() != SUBSELECT_ITEM &&
609 by Brian Aker
Dead class removal (more views)
941
           type() != REF_ITEM)
1 by brian
clean slate
942
  {
943
    /*
944
      Replace item with a reference so that we can easily calculate
945
      it (in case of sum functions) or copy it (in case of fields)
946
947
      The test above is to ensure we don't do a reference for things
948
      that are constants (PARAM_TABLE_BIT is in effect a constant)
949
      or already referenced (for example an item in HAVING)
950
      Exception is Item_direct_view_ref which we need to convert to
951
      Item_ref to allow fields from view being stored in tmp table.
952
    */
953
    Item_aggregate_ref *item_ref;
482 by Brian Aker
Remove uint.
954
    uint32_t el= fields.elements;
1 by brian
clean slate
955
    Item *real_itm= real_item();
956
957
    ref_pointer_array[el]= real_itm;
520.1.22 by Brian Aker
Second pass of thd cleanup
958
    if (!(item_ref= new Item_aggregate_ref(&session->lex->current_select->context,
1 by brian
clean slate
959
                                           ref_pointer_array + el, 0, name)))
960
      return;                                   // fatal_error is set
961
    if (type() == SUM_FUNC_ITEM)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
962
      item_ref->depended_from= ((Item_sum *) this)->depended_from();
1 by brian
clean slate
963
    fields.push_front(real_itm);
520.1.22 by Brian Aker
Second pass of thd cleanup
964
    session->change_item_tree(ref, item_ref);
1 by brian
clean slate
965
  }
966
}
967
968
/*
969
  Functions to convert item to field (for send_fields)
970
*/
971
972
/* ARGSUSED */
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
973
bool Item::fix_fields(Session *, Item **)
1 by brian
clean slate
974
{
975
976
  // We do not check fields which are fixed during construction
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
977
  assert(fixed == 0 || basic_const_item());
1 by brian
clean slate
978
  fixed= 1;
56 by brian
Next pass of true/false update.
979
  return false;
1 by brian
clean slate
980
}
981
982
983
/**
984
  Mark item and SELECT_LEXs as dependent if item was resolved in
985
  outer SELECT.
986
520.1.22 by Brian Aker
Second pass of thd cleanup
987
  @param session             thread handler
1 by brian
clean slate
988
  @param last            select from which current item depend
989
  @param current         current select
990
  @param resolved_item   item which was resolved in outer SELECT(for warning)
991
  @param mark_item       item which should be marked (can be differ in case of
992
                         substitution)
993
*/
994
642.1.1 by Lee
move functions from item.cc/item.h to item directory
995
void mark_as_dependent(Session *session, SELECT_LEX *last, SELECT_LEX *current,
1 by brian
clean slate
996
                              Item_ident *resolved_item,
997
                              Item_ident *mark_item)
998
{
999
  const char *db_name= (resolved_item->db_name ?
1000
                        resolved_item->db_name : "");
1001
  const char *table_name= (resolved_item->table_name ?
1002
                           resolved_item->table_name : "");
1003
  /* store pointer on SELECT_LEX from which item is dependent */
1004
  if (mark_item)
1005
    mark_item->depended_from= last;
1006
  current->mark_as_dependent(last);
520.1.22 by Brian Aker
Second pass of thd cleanup
1007
  if (session->lex->describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
1008
  {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1009
    char warn_buff[DRIZZLE_ERRMSG_SIZE];
1 by brian
clean slate
1010
    sprintf(warn_buff, ER(ER_WARN_FIELD_RESOLVED),
1011
            db_name, (db_name[0] ? "." : ""),
1012
            table_name, (table_name [0] ? "." : ""),
1013
            resolved_item->field_name,
1014
	    current->select_number, last->select_number);
520.1.22 by Brian Aker
Second pass of thd cleanup
1015
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
1016
		 ER_WARN_FIELD_RESOLVED, warn_buff);
1017
  }
1018
}
1019
1020
1021
/**
1022
  Mark range of selects and resolved identifier (field/reference)
1023
  item as dependent.
1024
520.1.22 by Brian Aker
Second pass of thd cleanup
1025
  @param session             thread handler
1 by brian
clean slate
1026
  @param last_select     select where resolved_item was resolved
1027
  @param current_sel     current select (select where resolved_item was placed)
1028
  @param found_field     field which was found during resolving
1029
  @param found_item      Item which was found during resolving (if resolved
1030
                         identifier belongs to VIEW)
1031
  @param resolved_item   Identifier which was resolved
1032
1033
  @note
1034
    We have to mark all items between current_sel (including) and
1035
    last_select (excluding) as dependend (select before last_select should
1036
    be marked with actual table mask used by resolved item, all other with
1037
    OUTER_REF_TABLE_BIT) and also write dependence information to Item of
1038
    resolved identifier.
1039
*/
1040
520.1.22 by Brian Aker
Second pass of thd cleanup
1041
void mark_select_range_as_dependent(Session *session,
1 by brian
clean slate
1042
                                    SELECT_LEX *last_select,
1043
                                    SELECT_LEX *current_sel,
1044
                                    Field *found_field, Item *found_item,
1045
                                    Item_ident *resolved_item)
1046
{
1047
  /*
1048
    Go from current SELECT to SELECT where field was resolved (it
1049
    have to be reachable from current SELECT, because it was already
1050
    done once when we resolved this field and cached result of
1051
    resolving)
1052
  */
1053
  SELECT_LEX *previous_select= current_sel;
1054
  for (; previous_select->outer_select() != last_select;
1055
       previous_select= previous_select->outer_select())
1056
  {
1057
    Item_subselect *prev_subselect_item=
1058
      previous_select->master_unit()->item;
1059
    prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
1060
    prev_subselect_item->const_item_cache= 0;
1061
  }
1062
  {
1063
    Item_subselect *prev_subselect_item=
1064
      previous_select->master_unit()->item;
1065
    Item_ident *dependent= resolved_item;
1066
    if (found_field == view_ref_found)
1067
    {
1068
      Item::Type type= found_item->type();
1069
      prev_subselect_item->used_tables_cache|=
1070
        found_item->used_tables();
1071
      dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
1072
                  (Item_ident*) found_item :
1073
                  0);
1074
    }
1075
    else
1076
      prev_subselect_item->used_tables_cache|=
1077
        found_field->table->map;
1078
    prev_subselect_item->const_item_cache= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
1079
    mark_as_dependent(session, last_select, current_sel, resolved_item,
1 by brian
clean slate
1080
                      dependent);
1081
  }
1082
}
1083
1084
1085
/**
1086
  Search a GROUP BY clause for a field with a certain name.
1087
1088
  Search the GROUP BY list for a column named as find_item. When searching
1089
  preference is given to columns that are qualified with the same table (and
1090
  database) name as the one being searched for.
1091
1092
  @param find_item     the item being searched for
1093
  @param group_list    GROUP BY clause
1094
1095
  @return
1096
    - the found item on success
1097
    - NULL if find_item is not in group_list
1098
*/
1099
327.2.3 by Brian Aker
Refactoring of class Table
1100
static Item** find_field_in_group_list(Item *find_item, order_st *group_list)
1 by brian
clean slate
1101
{
1102
  const char *db_name;
1103
  const char *table_name;
1104
  const char *field_name;
327.2.3 by Brian Aker
Refactoring of class Table
1105
  order_st      *found_group= NULL;
1 by brian
clean slate
1106
  int         found_match_degree= 0;
1107
  Item_ident *cur_field;
1108
  int         cur_match_degree= 0;
1109
  char        name_buff[NAME_LEN+1];
1110
1111
  if (find_item->type() == Item::FIELD_ITEM ||
1112
      find_item->type() == Item::REF_ITEM)
1113
  {
1114
    db_name=    ((Item_ident*) find_item)->db_name;
1115
    table_name= ((Item_ident*) find_item)->table_name;
1116
    field_name= ((Item_ident*) find_item)->field_name;
1117
  }
1118
  else
1119
    return NULL;
1120
1121
  if (db_name && lower_case_table_names)
1122
  {
1123
    /* Convert database to lower case for comparison */
629.5.4 by Toru Maesaka
Fourth pass of replacing MySQL's strmake() with libc calls
1124
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
1 by brian
clean slate
1125
    my_casedn_str(files_charset_info, name_buff);
1126
    db_name= name_buff;
1127
  }
1128
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1129
  assert(field_name != 0);
1 by brian
clean slate
1130
327.2.3 by Brian Aker
Refactoring of class Table
1131
  for (order_st *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
1 by brian
clean slate
1132
  {
1133
    if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM)
1134
    {
1135
      cur_field= (Item_ident*) *cur_group->item;
1136
      cur_match_degree= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1137
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1138
      assert(cur_field->field_name != 0);
1 by brian
clean slate
1139
1140
      if (!my_strcasecmp(system_charset_info,
1141
                         cur_field->field_name, field_name))
1142
        ++cur_match_degree;
1143
      else
1144
        continue;
1145
1146
      if (cur_field->table_name && table_name)
1147
      {
1148
        /* If field_name is qualified by a table name. */
1149
        if (my_strcasecmp(table_alias_charset, cur_field->table_name, table_name))
1150
          /* Same field names, different tables. */
1151
          return NULL;
1152
1153
        ++cur_match_degree;
1154
        if (cur_field->db_name && db_name)
1155
        {
1156
          /* If field_name is also qualified by a database name. */
1157
          if (strcmp(cur_field->db_name, db_name))
1158
            /* Same field names, different databases. */
1159
            return NULL;
1160
          ++cur_match_degree;
1161
        }
1162
      }
1163
1164
      if (cur_match_degree > found_match_degree)
1165
      {
1166
        found_match_degree= cur_match_degree;
1167
        found_group= cur_group;
1168
      }
1169
      else if (found_group && (cur_match_degree == found_match_degree) &&
1170
               ! (*(found_group->item))->eq(cur_field, 0))
1171
      {
1172
        /*
1173
          If the current resolve candidate matches equally well as the current
1174
          best match, they must reference the same column, otherwise the field
1175
          is ambiguous.
1176
        */
1177
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
520.1.22 by Brian Aker
Second pass of thd cleanup
1178
                 find_item->full_name(), current_session->where);
1 by brian
clean slate
1179
        return NULL;
1180
      }
1181
    }
1182
  }
1183
1184
  if (found_group)
1185
    return found_group->item;
1186
  else
1187
    return NULL;
1188
}
1189
1190
1191
/**
1192
  Resolve a column reference in a sub-select.
1193
1194
  Resolve a column reference (usually inside a HAVING clause) against the
1195
  SELECT and GROUP BY clauses of the query described by 'select'. The name
1196
  resolution algorithm searches both the SELECT and GROUP BY clauses, and in
1197
  case of a name conflict prefers GROUP BY column names over SELECT names. If
1198
  both clauses contain different fields with the same names, a warning is
1199
  issued that name of 'ref' is ambiguous. We extend ANSI SQL in that when no
1200
  GROUP BY column is found, then a HAVING name is resolved as a possibly
1201
  derived SELECT column. This extension is allowed only if the
1202
  MODE_ONLY_FULL_GROUP_BY sql mode isn't enabled.
1203
520.1.22 by Brian Aker
Second pass of thd cleanup
1204
  @param session     current thread
1 by brian
clean slate
1205
  @param ref     column reference being resolved
1206
  @param select  the select that ref is resolved against
1207
1208
  @note
1209
    The resolution procedure is:
1210
    - Search for a column or derived column named col_ref_i [in table T_j]
1211
    in the SELECT clause of Q.
1212
    - Search for a column named col_ref_i [in table T_j]
1213
    in the GROUP BY clause of Q.
1214
    - If found different columns with the same name in GROUP BY and SELECT
1215
    - issue a warning and return the GROUP BY column,
1216
    - otherwise
1217
    - if the MODE_ONLY_FULL_GROUP_BY mode is enabled return error
1218
    - else return the found SELECT column.
1219
1220
1221
  @return
1222
    - NULL - there was an error, and the error was already reported
1223
    - not_found_item - the item was not resolved, no error was reported
1224
    - resolved item - if the item was resolved
1225
*/
1226
642.1.1 by Lee
move functions from item.cc/item.h to item directory
1227
Item**
520.1.22 by Brian Aker
Second pass of thd cleanup
1228
resolve_ref_in_select_and_group(Session *session, Item_ident *ref, SELECT_LEX *select)
1 by brian
clean slate
1229
{
1230
  Item **group_by_ref= NULL;
1231
  Item **select_ref= NULL;
327.2.3 by Brian Aker
Refactoring of class Table
1232
  order_st *group_list= (order_st*) select->group_list.first;
56 by brian
Next pass of true/false update.
1233
  bool ambiguous_fields= false;
482 by Brian Aker
Remove uint.
1234
  uint32_t counter;
1 by brian
clean slate
1235
  enum_resolution_type resolution;
1236
1237
  /*
1238
    Search for a column or derived column named as 'ref' in the SELECT
1239
    clause of the current select.
1240
  */
1241
  if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()),
1242
                                      &counter, REPORT_EXCEPT_NOT_FOUND,
1243
                                      &resolution)))
1244
    return NULL; /* Some error occurred. */
1245
  if (resolution == RESOLVED_AGAINST_ALIAS)
56 by brian
Next pass of true/false update.
1246
    ref->alias_name_used= true;
1 by brian
clean slate
1247
1248
  /* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
1249
  if (select->having_fix_field && !ref->with_sum_func && group_list)
1250
  {
1251
    group_by_ref= find_field_in_group_list(ref, group_list);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1252
1 by brian
clean slate
1253
    /* Check if the fields found in SELECT and GROUP BY are the same field. */
1254
    if (group_by_ref && (select_ref != not_found_item) &&
1255
        !((*group_by_ref)->eq(*select_ref, 0)))
1256
    {
56 by brian
Next pass of true/false update.
1257
      ambiguous_fields= true;
520.1.22 by Brian Aker
Second pass of thd cleanup
1258
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
1 by brian
clean slate
1259
                          ER(ER_NON_UNIQ_ERROR), ref->full_name(),
520.1.22 by Brian Aker
Second pass of thd cleanup
1260
                          current_session->where);
1 by brian
clean slate
1261
1262
    }
1263
  }
1264
1265
  if (select_ref != not_found_item || group_by_ref)
1266
  {
1267
    if (select_ref != not_found_item && !ambiguous_fields)
1268
    {
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1269
      assert(*select_ref != 0);
1 by brian
clean slate
1270
      if (!select->ref_pointer_array[counter])
1271
      {
1272
        my_error(ER_ILLEGAL_REFERENCE, MYF(0),
1273
                 ref->name, "forward reference in item list");
1274
        return NULL;
1275
      }
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1276
      assert((*select_ref)->fixed);
1 by brian
clean slate
1277
      return (select->ref_pointer_array + counter);
1278
    }
1279
    if (group_by_ref)
1280
      return group_by_ref;
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1281
    assert(false);
1 by brian
clean slate
1282
    return NULL; /* So there is no compiler warning. */
1283
  }
1284
1285
  return (Item**) not_found_item;
1286
}
1287
1288
void Item::init_make_field(Send_field *tmp_field,
1289
			   enum enum_field_types field_type_arg)
1290
{
1291
  char *empty_name= (char*) "";
1292
  tmp_field->db_name=		empty_name;
1293
  tmp_field->org_table_name=	empty_name;
1294
  tmp_field->org_col_name=	empty_name;
1295
  tmp_field->table_name=	empty_name;
1296
  tmp_field->col_name=		name;
1297
  tmp_field->charsetnr=         collation.collation->number;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1298
  tmp_field->flags=             (maybe_null ? 0 : NOT_NULL_FLAG) |
1 by brian
clean slate
1299
                                (my_binary_compare(collation.collation) ?
1300
                                 BINARY_FLAG : 0);
1301
  tmp_field->type=              field_type_arg;
1302
  tmp_field->length=max_length;
1303
  tmp_field->decimals=decimals;
1304
}
1305
1306
void Item::make_field(Send_field *tmp_field)
1307
{
1308
  init_make_field(tmp_field, field_type());
1309
}
1310
1311
1312
enum_field_types Item::string_field_type() const
1313
{
240 by Brian Aker
Removed old/dead VARCHAR type from pre-5.0
1314
  enum_field_types f_type= DRIZZLE_TYPE_VARCHAR;
113 by Brian Aker
First pass on removing blob internals.
1315
  if (max_length >= 65536)
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1316
    f_type= DRIZZLE_TYPE_BLOB;
1 by brian
clean slate
1317
  return f_type;
1318
}
1319
1320
enum_field_types Item::field_type() const
1321
{
1322
  switch (result_type()) {
1323
  case STRING_RESULT:  return string_field_type();
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1324
  case INT_RESULT:     return DRIZZLE_TYPE_LONGLONG;
1325
  case DECIMAL_RESULT: return DRIZZLE_TYPE_NEWDECIMAL;
1326
  case REAL_RESULT:    return DRIZZLE_TYPE_DOUBLE;
1 by brian
clean slate
1327
  case ROW_RESULT:
1328
  default:
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1329
    assert(0);
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1330
    return DRIZZLE_TYPE_VARCHAR;
1 by brian
clean slate
1331
  }
1332
}
1333
1334
1335
bool Item::is_datetime()
1336
{
1337
  switch (field_type())
1338
  {
575.5.1 by David Axmark
Changed NEWDATE to DATE. One failing test but I think its somewhere else in the code
1339
    case DRIZZLE_TYPE_DATE:
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1340
    case DRIZZLE_TYPE_DATETIME:
1341
    case DRIZZLE_TYPE_TIMESTAMP:
56 by brian
Next pass of true/false update.
1342
      return true;
1 by brian
clean slate
1343
    default:
1344
      break;
1345
  }
56 by brian
Next pass of true/false update.
1346
  return false;
1 by brian
clean slate
1347
}
1348
1349
1350
String *Item::check_well_formed_result(String *str, bool send_error)
1351
{
1352
  /* Check whether we got a well-formed string */
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1353
  const CHARSET_INFO * const cs= str->charset();
1 by brian
clean slate
1354
  int well_formed_error;
482 by Brian Aker
Remove uint.
1355
  uint32_t wlen= cs->cset->well_formed_len(cs,
1 by brian
clean slate
1356
                                       str->ptr(), str->ptr() + str->length(),
1357
                                       str->length(), &well_formed_error);
1358
  if (wlen < str->length())
1359
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1360
    Session *session= current_session;
1 by brian
clean slate
1361
    char hexbuf[7];
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1362
    enum DRIZZLE_ERROR::enum_warning_level level;
482 by Brian Aker
Remove uint.
1363
    uint32_t diff= str->length() - wlen;
1 by brian
clean slate
1364
    set_if_smaller(diff, 3);
1365
    octet2hex(hexbuf, str->ptr() + wlen, diff);
1366
    if (send_error)
1367
    {
1368
      my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
1369
               cs->csname,  hexbuf);
1370
      return 0;
1371
    }
1372
    {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1373
      level= DRIZZLE_ERROR::WARN_LEVEL_ERROR;
1 by brian
clean slate
1374
      null_value= 1;
1375
      str= 0;
1376
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1377
    push_warning_printf(session, level, ER_INVALID_CHARACTER_STRING,
1 by brian
clean slate
1378
                        ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
1379
  }
1380
  return str;
1381
}
1382
1383
/*
1384
  Compare two items using a given collation
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1385
1 by brian
clean slate
1386
  SYNOPSIS
1387
    eq_by_collation()
1388
    item               item to compare with
56 by brian
Next pass of true/false update.
1389
    binary_cmp         true <-> compare as binaries
1 by brian
clean slate
1390
    cs                 collation to use when comparing strings
1391
1392
  DESCRIPTION
1393
    This method works exactly as Item::eq if the collation cs coincides with
1394
    the collation of the compared objects. Otherwise, first the collations that
1395
    differ from cs are replaced for cs and then the items are compared by
1396
    Item::eq. After the comparison the original collations of items are
1397
    restored.
1398
1399
  RETURN
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1400
    1    compared items has been detected as equal
1 by brian
clean slate
1401
    0    otherwise
1402
*/
1403
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1404
bool Item::eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO * const cs)
1 by brian
clean slate
1405
{
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1406
  const CHARSET_INFO *save_cs= 0;
1407
  const CHARSET_INFO *save_item_cs= 0;
1 by brian
clean slate
1408
  if (collation.collation != cs)
1409
  {
1410
    save_cs= collation.collation;
1411
    collation.collation= cs;
1412
  }
1413
  if (item->collation.collation != cs)
1414
  {
1415
    save_item_cs= item->collation.collation;
1416
    item->collation.collation= cs;
1417
  }
1418
  bool res= eq(item, binary_cmp);
1419
  if (save_cs)
1420
    collation.collation= save_cs;
1421
  if (save_item_cs)
1422
    item->collation.collation= save_item_cs;
1423
  return res;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1424
}
1 by brian
clean slate
1425
1426
1427
/**
1428
  Create a field to hold a string value from an item.
1429
1430
  If max_length > CONVERT_IF_BIGGER_TO_BLOB create a blob @n
1431
  If max_length > 0 create a varchar @n
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1432
  If max_length == 0 create a CHAR(0)
1 by brian
clean slate
1433
1434
  @param table		Table for which the field is created
1435
*/
1436
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1437
Field *Item::make_string_field(Table *table)
1 by brian
clean slate
1438
{
1439
  Field *field;
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1440
  assert(collation.collation);
1 by brian
clean slate
1441
  if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB)
1442
    field= new Field_blob(max_length, maybe_null, name,
1443
                          collation.collation);
241 by Brian Aker
First pass of CHAR removal.
1444
  else
1 by brian
clean slate
1445
    field= new Field_varstring(max_length, maybe_null, name, table->s,
1446
                               collation.collation);
241 by Brian Aker
First pass of CHAR removal.
1447
1 by brian
clean slate
1448
  if (field)
1449
    field->init(table);
1450
  return field;
1451
}
1452
1453
1454
/**
1455
  Create a field based on field_type of argument.
1456
1457
  For now, this is only used to create a field for
1458
  IFNULL(x,something) and time functions
1459
1460
  @retval
1461
    NULL  error
1462
  @retval
1463
    \#    Created field
1464
*/
1465
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
1466
Field *Item::tmp_table_field_from_field_type(Table *table, bool)
1 by brian
clean slate
1467
{
1468
  /*
1469
    The field functions defines a field to be not null if null_ptr is not 0
1470
  */
481 by Brian Aker
Remove all of uchar.
1471
  unsigned char *null_ptr= maybe_null ? (unsigned char*) "" : 0;
1 by brian
clean slate
1472
  Field *field;
1473
1474
  switch (field_type()) {
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1475
  case DRIZZLE_TYPE_NEWDECIMAL:
481 by Brian Aker
Remove all of uchar.
1476
    field= new Field_new_decimal((unsigned char*) 0, max_length, null_ptr, 0,
1 by brian
clean slate
1477
                                 Field::NONE, name, decimals, 0,
1478
                                 unsigned_flag);
1479
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1480
  case DRIZZLE_TYPE_LONG:
481 by Brian Aker
Remove all of uchar.
1481
    field= new Field_long((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE,
1 by brian
clean slate
1482
			  name, 0, unsigned_flag);
1483
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1484
  case DRIZZLE_TYPE_LONGLONG:
481 by Brian Aker
Remove all of uchar.
1485
    field= new Field_int64_t((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE,
1 by brian
clean slate
1486
			      name, 0, unsigned_flag);
1487
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1488
  case DRIZZLE_TYPE_DOUBLE:
481 by Brian Aker
Remove all of uchar.
1489
    field= new Field_double((unsigned char*) 0, max_length, null_ptr, 0, Field::NONE,
1 by brian
clean slate
1490
			    name, decimals, 0, unsigned_flag);
1491
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1492
  case DRIZZLE_TYPE_NULL:
481 by Brian Aker
Remove all of uchar.
1493
    field= new Field_null((unsigned char*) 0, max_length, Field::NONE,
1 by brian
clean slate
1494
			  name, &my_charset_bin);
1495
    break;
575.5.1 by David Axmark
Changed NEWDATE to DATE. One failing test but I think its somewhere else in the code
1496
  case DRIZZLE_TYPE_DATE:
1497
    field= new Field_date(maybe_null, name, &my_charset_bin);
1 by brian
clean slate
1498
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1499
  case DRIZZLE_TYPE_TIME:
1 by brian
clean slate
1500
    field= new Field_time(maybe_null, name, &my_charset_bin);
1501
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1502
  case DRIZZLE_TYPE_TIMESTAMP:
1 by brian
clean slate
1503
    field= new Field_timestamp(maybe_null, name, &my_charset_bin);
1504
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1505
  case DRIZZLE_TYPE_DATETIME:
1 by brian
clean slate
1506
    field= new Field_datetime(maybe_null, name, &my_charset_bin);
1507
    break;
1508
  default:
1509
    /* This case should never be chosen */
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1510
    assert(0);
1 by brian
clean slate
1511
    /* Fall through to make_string_field() */
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1512
  case DRIZZLE_TYPE_ENUM:
1513
  case DRIZZLE_TYPE_VARCHAR:
1 by brian
clean slate
1514
    return make_string_field(table);
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1515
  case DRIZZLE_TYPE_BLOB:
1 by brian
clean slate
1516
    if (this->type() == Item::TYPE_HOLDER)
1517
      field= new Field_blob(max_length, maybe_null, name, collation.collation,
1518
                            1);
1519
    else
1520
      field= new Field_blob(max_length, maybe_null, name, collation.collation);
1521
    break;					// Blob handled outside of case
1522
  }
1523
  if (field)
1524
    field->init(table);
1525
  return field;
1526
}
1527
1528
1529
/*
1530
  This implementation can lose str_value content, so if the
1531
  Item uses str_value to store something, it should
1532
  reimplement it's ::save_in_field() as Item_string, for example, does
1533
*/
1534
1535
int Item::save_in_field(Field *field, bool no_conversions)
1536
{
1537
  int error;
1538
  if (result_type() == STRING_RESULT)
1539
  {
1540
    String *result;
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1541
    const CHARSET_INFO * const cs= collation.collation;
1 by brian
clean slate
1542
    char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
1543
    str_value.set_quick(buff, sizeof(buff), cs);
1544
    result=val_str(&str_value);
1545
    if (null_value)
1546
    {
1547
      str_value.set_quick(0, 0, cs);
1548
      return set_field_to_null_with_conversions(field, no_conversions);
1549
    }
1550
56 by brian
Next pass of true/false update.
1551
    /* NOTE: If null_value == false, "result" must be not NULL.  */
1 by brian
clean slate
1552
1553
    field->set_notnull();
1554
    error=field->store(result->ptr(),result->length(),cs);
1555
    str_value.set_quick(0, 0, cs);
1556
  }
1557
  else if (result_type() == REAL_RESULT &&
1558
           field->result_type() == STRING_RESULT)
1559
  {
1560
    double nr= val_real();
1561
    if (null_value)
1562
      return set_field_to_null_with_conversions(field, no_conversions);
1563
    field->set_notnull();
1564
    error= field->store(nr);
1565
  }
1566
  else if (result_type() == REAL_RESULT)
1567
  {
1568
    double nr= val_real();
1569
    if (null_value)
1570
      return set_field_to_null(field);
1571
    field->set_notnull();
1572
    error=field->store(nr);
1573
  }
1574
  else if (result_type() == DECIMAL_RESULT)
1575
  {
1576
    my_decimal decimal_value;
1577
    my_decimal *value= val_decimal(&decimal_value);
1578
    if (null_value)
1579
      return set_field_to_null_with_conversions(field, no_conversions);
1580
    field->set_notnull();
1581
    error=field->store_decimal(value);
1582
  }
1583
  else
1584
  {
152 by Brian Aker
longlong replacement
1585
    int64_t nr=val_int();
1 by brian
clean slate
1586
    if (null_value)
1587
      return set_field_to_null_with_conversions(field, no_conversions);
1588
    field->set_notnull();
1589
    error=field->store(nr, unsigned_flag);
1590
  }
1591
  return error;
1592
}
1593
1594
1595
/**
1596
  This is only called from items that is not of type item_field.
1597
*/
1598
1599
bool Item::send(Protocol *protocol, String *buffer)
1600
{
1601
  bool result= false;
1602
  enum_field_types f_type;
1603
1604
  switch ((f_type=field_type())) {
1605
  default:
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1606
  case DRIZZLE_TYPE_NULL:
1607
  case DRIZZLE_TYPE_ENUM:
1608
  case DRIZZLE_TYPE_BLOB:
1609
  case DRIZZLE_TYPE_VARCHAR:
1610
  case DRIZZLE_TYPE_NEWDECIMAL:
1 by brian
clean slate
1611
  {
1612
    String *res;
1613
    if ((res=val_str(buffer)))
1614
      result= protocol->store(res->ptr(),res->length(),res->charset());
1615
    break;
1616
  }
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1617
  case DRIZZLE_TYPE_LONG:
1 by brian
clean slate
1618
  {
152 by Brian Aker
longlong replacement
1619
    int64_t nr;
1 by brian
clean slate
1620
    nr= val_int();
1621
    if (!null_value)
1622
      result= protocol->store_long(nr);
1623
    break;
1624
  }
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1625
  case DRIZZLE_TYPE_LONGLONG:
1 by brian
clean slate
1626
  {
152 by Brian Aker
longlong replacement
1627
    int64_t nr;
1 by brian
clean slate
1628
    nr= val_int();
1629
    if (!null_value)
152 by Brian Aker
longlong replacement
1630
      result= protocol->store_int64_t(nr, unsigned_flag);
1 by brian
clean slate
1631
    break;
1632
  }
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1633
  case DRIZZLE_TYPE_DOUBLE:
1 by brian
clean slate
1634
  {
1635
    double nr= val_real();
1636
    if (!null_value)
1637
      result= protocol->store(nr, decimals, buffer);
1638
    break;
1639
  }
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1640
  case DRIZZLE_TYPE_DATETIME:
1641
  case DRIZZLE_TYPE_TIMESTAMP:
1 by brian
clean slate
1642
  {
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
1643
    DRIZZLE_TIME tm;
1 by brian
clean slate
1644
    get_date(&tm, TIME_FUZZY_DATE);
1645
    if (!null_value)
1646
    {
575.5.1 by David Axmark
Changed NEWDATE to DATE. One failing test but I think its somewhere else in the code
1647
      if (f_type == DRIZZLE_TYPE_DATE)
1 by brian
clean slate
1648
	return protocol->store_date(&tm);
1649
      else
1650
	result= protocol->store(&tm);
1651
    }
1652
    break;
1653
  }
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1654
  case DRIZZLE_TYPE_TIME:
1 by brian
clean slate
1655
  {
236.1.24 by Monty Taylor
Renamed MYSQL_TIME to DRIZZLE_TIME.
1656
    DRIZZLE_TIME tm;
1 by brian
clean slate
1657
    get_time(&tm);
1658
    if (!null_value)
1659
      result= protocol->store_time(&tm);
1660
    break;
1661
  }
1662
  }
1663
  if (null_value)
1664
    result= protocol->store_null();
1665
  return result;
1666
}
1667
1668
1669
bool Item_default_value::eq(const Item *item, bool binary_cmp) const
1670
{
77.1.15 by Monty Taylor
Bunch of warning cleanups.
1671
  return item->type() == DEFAULT_VALUE_ITEM &&
1 by brian
clean slate
1672
    ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
1673
}
1674
1675
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
1676
bool Item_default_value::fix_fields(Session *session, Item **)
1 by brian
clean slate
1677
{
1678
  Item *real_arg;
1679
  Item_field *field_arg;
1680
  Field *def_field;
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1681
  assert(fixed == 0);
1 by brian
clean slate
1682
1683
  if (!arg)
1684
  {
1685
    fixed= 1;
56 by brian
Next pass of true/false update.
1686
    return false;
1 by brian
clean slate
1687
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
1688
  if (!arg->fixed && arg->fix_fields(session, &arg))
1 by brian
clean slate
1689
    goto error;
1690
1691
1692
  real_arg= arg->real_item();
1693
  if (real_arg->type() != FIELD_ITEM)
1694
  {
1695
    my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->name);
1696
    goto error;
1697
  }
1698
1699
  field_arg= (Item_field *)real_arg;
1700
  if (field_arg->field->flags & NO_DEFAULT_VALUE_FLAG)
1701
  {
1702
    my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), field_arg->field->field_name);
1703
    goto error;
1704
  }
1705
  if (!(def_field= (Field*) sql_alloc(field_arg->field->size_of())))
1706
    goto error;
1707
  memcpy(def_field, field_arg->field, field_arg->field->size_of());
1708
  def_field->move_field_offset((my_ptrdiff_t)
1709
                               (def_field->table->s->default_values -
1710
                                def_field->table->record[0]));
1711
  set_field(def_field);
56 by brian
Next pass of true/false update.
1712
  return false;
1 by brian
clean slate
1713
1714
error:
520.1.22 by Brian Aker
Second pass of thd cleanup
1715
  context->process_error(session);
56 by brian
Next pass of true/false update.
1716
  return true;
1 by brian
clean slate
1717
}
1718
1719
1720
void Item_default_value::print(String *str, enum_query_type query_type)
1721
{
1722
  if (!arg)
1723
  {
1724
    str->append(STRING_WITH_LEN("default"));
1725
    return;
1726
  }
1727
  str->append(STRING_WITH_LEN("default("));
1728
  arg->print(str, query_type);
1729
  str->append(')');
1730
}
1731
1732
1733
int Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
1734
{
1735
  if (!arg)
1736
  {
1737
    if (field_arg->flags & NO_DEFAULT_VALUE_FLAG)
1738
    {
1739
      if (field_arg->reset())
1740
      {
1741
        my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
1742
                   ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
1743
        return -1;
1744
      }
1745
1746
      {
1747
        push_warning_printf(field_arg->table->in_use,
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1748
                            DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
1749
                            ER_NO_DEFAULT_FOR_FIELD,
1750
                            ER(ER_NO_DEFAULT_FOR_FIELD),
1751
                            field_arg->field_name);
1752
      }
1753
      return 1;
1754
    }
1755
    field_arg->set_default();
1756
    return 0;
1757
  }
1758
  return Item_field::save_in_field(field_arg, no_conversions);
1759
}
1760
1761
1762
/**
1763
  This method like the walk method traverses the item tree, but at the
1764
  same time it can replace some nodes in the tree.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1765
*/
1 by brian
clean slate
1766
481 by Brian Aker
Remove all of uchar.
1767
Item *Item_default_value::transform(Item_transformer transformer, unsigned char *args)
1 by brian
clean slate
1768
{
1769
  Item *new_item= arg->transform(transformer, args);
1770
  if (!new_item)
1771
    return 0;
1772
1773
  /*
520.1.21 by Brian Aker
THD -> Session rename
1774
    Session::change_item_tree() should be called only if the tree was
1 by brian
clean slate
1775
    really transformed, i.e. when a new item has been created.
1776
    Otherwise we'll be allocating a lot of unnecessary memory for
1777
    change records at each execution.
1778
  */
1779
  if (arg != new_item)
520.1.22 by Brian Aker
Second pass of thd cleanup
1780
    current_session->change_item_tree(&arg, new_item);
1 by brian
clean slate
1781
  return (this->*transformer)(args);
1782
}
1783
1784
Item_result item_cmp_type(Item_result a,Item_result b)
1785
{
1786
  if (a == STRING_RESULT && b == STRING_RESULT)
1787
    return STRING_RESULT;
1788
  if (a == INT_RESULT && b == INT_RESULT)
1789
    return INT_RESULT;
1790
  else if (a == ROW_RESULT || b == ROW_RESULT)
1791
    return ROW_RESULT;
1792
  if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
1793
      (b == INT_RESULT || b == DECIMAL_RESULT))
1794
    return DECIMAL_RESULT;
1795
  return REAL_RESULT;
1796
}
1797
1798
520.1.22 by Brian Aker
Second pass of thd cleanup
1799
void resolve_const_item(Session *session, Item **ref, Item *comp_item)
1 by brian
clean slate
1800
{
1801
  Item *item= *ref;
1802
  Item *new_item= NULL;
1803
  if (item->basic_const_item())
1804
    return;                                     // Can't be better
1805
  Item_result res_type=item_cmp_type(comp_item->result_type(),
1806
				     item->result_type());
1807
  char *name=item->name;			// Alloced by sql_alloc
1808
1809
  switch (res_type) {
1810
  case STRING_RESULT:
1811
  {
1812
    char buff[MAX_FIELD_WIDTH];
1813
    String tmp(buff,sizeof(buff),&my_charset_bin),*result;
1814
    result=item->val_str(&tmp);
1815
    if (item->null_value)
1816
      new_item= new Item_null(name);
1817
    else
1818
    {
482 by Brian Aker
Remove uint.
1819
      uint32_t length= result->length();
1 by brian
clean slate
1820
      char *tmp_str= sql_strmake(result->ptr(), length);
1821
      new_item= new Item_string(name, tmp_str, length, result->charset());
1822
    }
1823
    break;
1824
  }
1825
  case INT_RESULT:
1826
  {
152 by Brian Aker
longlong replacement
1827
    int64_t result=item->val_int();
482 by Brian Aker
Remove uint.
1828
    uint32_t length=item->max_length;
1 by brian
clean slate
1829
    bool null_value=item->null_value;
1830
    new_item= (null_value ? (Item*) new Item_null(name) :
1831
               (Item*) new Item_int(name, result, length));
1832
    break;
1833
  }
1834
  case ROW_RESULT:
1835
  if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
1836
  {
1837
    /*
1838
      Substitute constants only in Item_rows. Don't affect other Items
1839
      with ROW_RESULT (eg Item_singlerow_subselect).
1840
1841
      For such Items more optimal is to detect if it is constant and replace
1842
      it with Item_row. This would optimize queries like this:
1843
      SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
1844
    */
1845
    Item_row *item_row= (Item_row*) item;
1846
    Item_row *comp_item_row= (Item_row*) comp_item;
482 by Brian Aker
Remove uint.
1847
    uint32_t col;
1 by brian
clean slate
1848
    new_item= 0;
1849
    /*
1850
      If item and comp_item are both Item_rows and have same number of cols
1851
      then process items in Item_row one by one.
1852
      We can't ignore NULL values here as this item may be used with <=>, in
1853
      which case NULL's are significant.
1854
    */
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1855
    assert(item->result_type() == comp_item->result_type());
1856
    assert(item_row->cols() == comp_item_row->cols());
1 by brian
clean slate
1857
    col= item_row->cols();
1858
    while (col-- > 0)
520.1.22 by Brian Aker
Second pass of thd cleanup
1859
      resolve_const_item(session, item_row->addr(col),
1 by brian
clean slate
1860
                         comp_item_row->element_index(col));
1861
    break;
1862
  }
1863
  /* Fallthrough */
1864
  case REAL_RESULT:
1865
  {						// It must REAL_RESULT
1866
    double result= item->val_real();
482 by Brian Aker
Remove uint.
1867
    uint32_t length=item->max_length,decimals=item->decimals;
1 by brian
clean slate
1868
    bool null_value=item->null_value;
1869
    new_item= (null_value ? (Item*) new Item_null(name) : (Item*)
1870
               new Item_float(name, result, decimals, length));
1871
    break;
1872
  }
1873
  case DECIMAL_RESULT:
1874
  {
1875
    my_decimal decimal_value;
1876
    my_decimal *result= item->val_decimal(&decimal_value);
482 by Brian Aker
Remove uint.
1877
    uint32_t length= item->max_length, decimals= item->decimals;
1 by brian
clean slate
1878
    bool null_value= item->null_value;
1879
    new_item= (null_value ?
1880
               (Item*) new Item_null(name) :
1881
               (Item*) new Item_decimal(name, result, length, decimals));
1882
    break;
1883
  }
1884
  default:
51.1.55 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE - 1st clean pass on item.h/cc
1885
    assert(0);
1 by brian
clean slate
1886
  }
1887
  if (new_item)
520.1.22 by Brian Aker
Second pass of thd cleanup
1888
    session->change_item_tree(ref, new_item);
1 by brian
clean slate
1889
}
1890
1891
/**
1892
  Return true if the value stored in the field is equal to the const
1893
  item.
1894
1895
  We need to use this on the range optimizer because in some cases
1896
  we can't store the value in the field without some precision/character loss.
1897
*/
1898
1899
bool field_is_equal_to_item(Field *field,Item *item)
1900
{
1901
1902
  Item_result res_type=item_cmp_type(field->result_type(),
1903
				     item->result_type());
1904
  if (res_type == STRING_RESULT)
1905
  {
1906
    char item_buff[MAX_FIELD_WIDTH];
1907
    char field_buff[MAX_FIELD_WIDTH];
1908
    String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result;
1909
    String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
1910
    item_result=item->val_str(&item_tmp);
1911
    if (item->null_value)
1912
      return 1;					// This must be true
1913
    field->val_str(&field_tmp);
1914
    return !stringcmp(&field_tmp,item_result);
1915
  }
1916
  if (res_type == INT_RESULT)
1917
    return 1;					// Both where of type int
1918
  if (res_type == DECIMAL_RESULT)
1919
  {
1920
    my_decimal item_buf, *item_val,
1921
               field_buf, *field_val;
1922
    item_val= item->val_decimal(&item_buf);
1923
    if (item->null_value)
1924
      return 1;					// This must be true
1925
    field_val= field->val_decimal(&field_buf);
1926
    return !my_decimal_cmp(item_val, field_val);
1927
  }
1928
  double result= item->val_real();
1929
  if (item->null_value)
1930
    return 1;
1931
  return result == field->val_real();
1932
}
1933
1934
/**
1935
  Dummy error processor used by default by Name_resolution_context.
1936
1937
  @note
1938
    do nothing
1939
*/
1940
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
1941
void dummy_error_processor(Session *, void *)
1 by brian
clean slate
1942
{}
1943
1944
/**
575.4.7 by Monty Taylor
More header cleanup.
1945
  Create field for temporary table using type of given item.
1946
1947
  @param session                   Thread handler
1948
  @param item                  Item to create a field for
1949
  @param table                 Temporary table
1950
  @param copy_func             If set and item is a function, store copy of
1951
                               item in this array
1952
  @param modify_item           1 if item->result_field should point to new
1953
                               item. This is relevent for how fill_record()
1954
                               is going to work:
1955
                               If modify_item is 1 then fill_record() will
1956
                               update the record in the original table.
1957
                               If modify_item is 0 then fill_record() will
1958
                               update the temporary table
1959
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
1960
                               field instead of blob.
1961
1962
  @retval
1963
    0  on error
1964
  @retval
1965
    new_created field
1966
*/
1967
1968
static Field *create_tmp_field_from_item(Session *,
1969
                                         Item *item, Table *table,
1970
                                         Item ***copy_func, bool modify_item,
1971
                                         uint32_t convert_blob_length)
1972
{
1973
  bool maybe_null= item->maybe_null;
1974
  Field *new_field;
1975
1976
  switch (item->result_type()) {
1977
  case REAL_RESULT:
1978
    new_field= new Field_double(item->max_length, maybe_null,
1979
                                item->name, item->decimals, true);
1980
    break;
1981
  case INT_RESULT:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1982
    /*
575.4.7 by Monty Taylor
More header cleanup.
1983
      Select an integer type with the minimal fit precision.
1984
      MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1985
      Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into
1986
      Field_long : make them Field_int64_t.
575.4.7 by Monty Taylor
More header cleanup.
1987
    */
1988
    if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
1989
      new_field=new Field_int64_t(item->max_length, maybe_null,
1990
                                   item->name, item->unsigned_flag);
1991
    else
1992
      new_field=new Field_long(item->max_length, maybe_null,
1993
                               item->name, item->unsigned_flag);
1994
    break;
1995
  case STRING_RESULT:
1996
    assert(item->collation.collation);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1997
575.4.7 by Monty Taylor
More header cleanup.
1998
    enum enum_field_types type;
1999
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2000
      DATE/TIME fields have STRING_RESULT result type.
575.4.7 by Monty Taylor
More header cleanup.
2001
      To preserve type they needed to be handled separately.
2002
    */
2003
    if ((type= item->field_type()) == DRIZZLE_TYPE_DATETIME ||
584.1.3 by Monty Taylor
Merged from David.
2004
        type == DRIZZLE_TYPE_TIME || type == DRIZZLE_TYPE_DATE ||
575.4.7 by Monty Taylor
More header cleanup.
2005
        type == DRIZZLE_TYPE_TIMESTAMP)
2006
      new_field= item->tmp_table_field_from_field_type(table, 1);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2007
    /*
2008
      Make sure that the blob fits into a Field_varstring which has
2009
      2-byte lenght.
575.4.7 by Monty Taylor
More header cleanup.
2010
    */
2011
    else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2012
             convert_blob_length <= Field_varstring::MAX_SIZE &&
575.4.7 by Monty Taylor
More header cleanup.
2013
             convert_blob_length)
2014
      new_field= new Field_varstring(convert_blob_length, maybe_null,
2015
                                     item->name, table->s,
2016
                                     item->collation.collation);
2017
    else
2018
      new_field= item->make_string_field(table);
2019
    new_field->set_derivation(item->collation.derivation);
2020
    break;
2021
  case DECIMAL_RESULT:
2022
  {
2023
    uint8_t dec= item->decimals;
2024
    uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
2025
    uint32_t len= item->max_length;
2026
2027
    /*
2028
      Trying to put too many digits overall in a DECIMAL(prec,dec)
2029
      will always throw a warning. We must limit dec to
2030
      DECIMAL_MAX_SCALE however to prevent an assert() later.
2031
    */
2032
2033
    if (dec > 0)
2034
    {
2035
      signed int overflow;
2036
2037
      dec= cmin(dec, (uint8_t)DECIMAL_MAX_SCALE);
2038
2039
      /*
2040
        If the value still overflows the field with the corrected dec,
2041
        we'll throw out decimals rather than integers. This is still
2042
        bad and of course throws a truncation warning.
2043
        +1: for decimal point
2044
      */
2045
2046
      overflow= my_decimal_precision_to_length(intg + dec, dec,
2047
                                               item->unsigned_flag) - len;
2048
2049
      if (overflow > 0)
2050
        dec= cmax(0, dec - overflow);            // too long, discard fract
2051
      else
2052
        len -= item->decimals - dec;            // corrected value fits
2053
    }
2054
2055
    new_field= new Field_new_decimal(len, maybe_null, item->name,
2056
                                     dec, item->unsigned_flag);
2057
    break;
2058
  }
2059
  case ROW_RESULT:
2060
  default:
2061
    // This case should never be choosen
2062
    assert(0);
2063
    new_field= 0;
2064
    break;
2065
  }
2066
  if (new_field)
2067
    new_field->init(table);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2068
575.4.7 by Monty Taylor
More header cleanup.
2069
  if (copy_func && item->is_result_field())
2070
    *((*copy_func)++) = item;			// Save for copy_funcs
2071
  if (modify_item)
2072
    item->set_result_field(new_field);
2073
  if (item->type() == Item::NULL_ITEM)
2074
    new_field->is_created_from_null_item= true;
2075
  return new_field;
2076
}
2077
2078
Field *create_tmp_field(Session *session, Table *table,Item *item,
2079
                        Item::Type type, Item ***copy_func, Field **from_field,
2080
                        Field **default_field, bool group, bool modify_item,
2081
                        bool, bool make_copy_field,
2082
                        uint32_t convert_blob_length)
2083
{
2084
  Field *result;
2085
  Item::Type orig_type= type;
2086
  Item *orig_item= 0;
2087
2088
  if (type != Item::FIELD_ITEM &&
2089
      item->real_item()->type() == Item::FIELD_ITEM)
2090
  {
2091
    orig_item= item;
2092
    item= item->real_item();
2093
    type= Item::FIELD_ITEM;
2094
  }
2095
2096
  switch (type) {
2097
  case Item::SUM_FUNC_ITEM:
2098
  {
2099
    Item_sum *item_sum=(Item_sum*) item;
2100
    result= item_sum->create_tmp_field(group, table, convert_blob_length);
2101
    if (!result)
2102
      my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
2103
    return result;
2104
  }
2105
  case Item::FIELD_ITEM:
2106
  case Item::DEFAULT_VALUE_ITEM:
2107
  {
2108
    Item_field *field= (Item_field*) item;
2109
    bool orig_modify= modify_item;
2110
    if (orig_type == Item::REF_ITEM)
2111
      modify_item= 0;
2112
    /*
2113
      If item have to be able to store NULLs but underlaid field can't do it,
2114
      create_tmp_field_from_field() can't be used for tmp field creation.
2115
    */
2116
    if (field->maybe_null && !field->field->maybe_null())
2117
    {
2118
      result= create_tmp_field_from_item(session, item, table, NULL,
2119
                                         modify_item, convert_blob_length);
2120
      *from_field= field->field;
2121
      if (result && modify_item)
2122
        field->result_field= result;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2123
    }
575.4.7 by Monty Taylor
More header cleanup.
2124
    else
2125
      result= create_tmp_field_from_field(session, (*from_field= field->field),
2126
                                          orig_item ? orig_item->name :
2127
                                          item->name,
2128
                                          table,
2129
                                          modify_item ? field :
2130
                                          NULL,
2131
                                          convert_blob_length);
2132
    if (orig_type == Item::REF_ITEM && orig_modify)
2133
      ((Item_ref*)orig_item)->set_result_field(result);
2134
    if (field->field->eq_def(result))
2135
      *default_field= field->field;
2136
    return result;
2137
  }
2138
  /* Fall through */
2139
  case Item::FUNC_ITEM:
2140
    /* Fall through */
2141
  case Item::COND_ITEM:
2142
  case Item::FIELD_AVG_ITEM:
2143
  case Item::FIELD_STD_ITEM:
2144
  case Item::SUBSELECT_ITEM:
2145
    /* The following can only happen with 'CREATE TABLE ... SELECT' */
2146
  case Item::PROC_ITEM:
2147
  case Item::INT_ITEM:
2148
  case Item::REAL_ITEM:
2149
  case Item::DECIMAL_ITEM:
2150
  case Item::STRING_ITEM:
2151
  case Item::REF_ITEM:
2152
  case Item::NULL_ITEM:
2153
  case Item::VARBIN_ITEM:
2154
    if (make_copy_field)
2155
    {
2156
      assert(((Item_result_field*)item)->result_field);
2157
      *from_field= ((Item_result_field*)item)->result_field;
2158
    }
2159
    return create_tmp_field_from_item(session, item, table,
2160
                                      (make_copy_field ? 0 : copy_func),
2161
                                       modify_item, convert_blob_length);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2162
  case Item::TYPE_HOLDER:
575.4.7 by Monty Taylor
More header cleanup.
2163
    result= ((Item_type_holder *)item)->make_field_by_type(table);
2164
    result->set_derivation(item->collation.derivation);
2165
    return result;
2166
  default:					// Dosen't have to be stored
2167
    return 0;
2168
  }
2169
}
2170
2171
2172
/**
1 by brian
clean slate
2173
  Wrapper of hide_view_error call for Name_resolution_context error
2174
  processor.
2175
2176
  @note
2177
    hide view underlying tables details in error messages
2178
*/
2179
2180
/*****************************************************************************
2181
** Instantiate templates
2182
*****************************************************************************/
2183
2184
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
2185
template class List<Item>;
2186
template class List_iterator<Item>;
2187
template class List_iterator_fast<Item>;
2188
template class List_iterator_fast<Item_field>;
2189
template class List<List_item>;
2190
#endif