~drizzle-trunk/drizzle/development

642.1.1 by Lee
move functions from item.cc/item.h to item directory
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 *
4
 *  Copyright (C) 2008 Sun Microsystems
5
 *
6
 *  This program is free software; you can redistribute it and/or modify
7
 *  it under the terms of the GNU General Public License as published by
8
 *  the Free Software Foundation; version 2 of the License.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, write to the Free Software
17
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
 */
19
20
#include <drizzled/server_includes.h>
21
#include CSTDINT_H
22
#include <drizzled/session.h>
23
#include <drizzled/table.h>
24
#include <drizzled/error.h>
25
#include <drizzled/sql_base.h>
26
#include <drizzled/sql_select.h>
27
#include <drizzled/item/cmpfunc.h>
28
#include <drizzled/item/field.h>
675 by Brian Aker
Cleanup around item includes.
29
#include <drizzled/item/outer_ref.h>
642.1.1 by Lee
move functions from item.cc/item.h to item directory
30
31
32
/**
33
  Store the pointer to this item field into a list if not already there.
34
35
  The method is used by Item::walk to collect all unique Item_field objects
36
  from a tree of Items into a set of items represented as a list.
37
38
  Item_cond::walk() and Item_func::walk() stop the evaluation of the
39
  processor function for its arguments once the processor returns
40
  true.Therefore in order to force this method being called for all item
41
  arguments in a condition the method must return false.
42
43
  @param arg  pointer to a List<Item_field>
44
45
  @return
46
    false to force the evaluation of collect_item_field_processor
47
    for the subsequent items.
48
*/
49
50
bool Item_field::collect_item_field_processor(unsigned char *arg)
51
{
52
  List<Item_field> *item_list= (List<Item_field>*) arg;
53
  List_iterator<Item_field> item_list_it(*item_list);
54
  Item_field *curr_item;
55
  while ((curr_item= item_list_it++))
56
  {
57
    if (curr_item->eq(this, 1))
58
      return(false); /* Already in the set. */
59
  }
60
  item_list->push_back(this);
61
  return(false);
62
}
63
64
65
/**
66
  Check if an Item_field references some field from a list of fields.
67
68
  Check whether the Item_field represented by 'this' references any
69
  of the fields in the keyparts passed via 'arg'. Used with the
70
  method Item::walk() to test whether any keypart in a sequence of
71
  keyparts is referenced in an expression.
72
73
  @param arg   Field being compared, arg must be of type Field
74
75
  @retval
76
    true  if 'this' references the field 'arg'
77
  @retval
78
    false otherwise
79
*/
80
81
bool Item_field::find_item_in_field_list_processor(unsigned char *arg)
82
{
83
  KEY_PART_INFO *first_non_group_part= *((KEY_PART_INFO **) arg);
84
  KEY_PART_INFO *last_part= *(((KEY_PART_INFO **) arg) + 1);
85
  KEY_PART_INFO *cur_part;
86
87
  for (cur_part= first_non_group_part; cur_part != last_part; cur_part++)
88
  {
89
    if (field->eq(cur_part->field))
90
      return true;
91
  }
92
  return false;
93
}
94
95
96
/*
97
  Mark field in read_map
98
99
  NOTES
100
    This is used by filesort to register used fields in a a temporary
101
    column read set or to register used fields in a view
102
*/
103
104
bool Item_field::register_field_in_read_map(unsigned char *arg)
105
{
106
  Table *table= (Table *) arg;
107
  if (field->table == table || !table)
1005.2.9 by Monty Taylor
Removed register_field_in_bitmap - unused.
108
    field->table->setReadSet(field->field_index);
1005.2.3 by Monty Taylor
Further reversion of P.
109
642.1.1 by Lee
move functions from item.cc/item.h to item directory
110
  return 0;
111
}
112
113
114
Item_field *Item::filed_for_view_update()
115
{
116
  return 0;
117
}
118
119
Item_field::Item_field(Field *f)
120
  :Item_ident(0, NULL, *f->table_name, f->field_name),
121
   item_equal(0), no_const_subst(0),
122
   have_privileges(0), any_privileges(0)
123
{
124
  set_field(f);
125
  /*
126
    field_name and table_name should not point to garbage
127
    if this item is to be reused
128
  */
129
  orig_table_name= orig_field_name= "";
130
}
131
132
133
/**
134
  Constructor used inside setup_wild().
135
136
  Ensures that field, table, and database names will live as long as
137
  Item_field (this is important in prepared statements).
138
*/
139
140
Item_field::Item_field(Session *, Name_resolution_context *context_arg,
141
                       Field *f)
142
  :Item_ident(context_arg, f->table->s->db.str, *f->table_name, f->field_name),
143
   item_equal(0), no_const_subst(0),
144
   have_privileges(0), any_privileges(0)
145
{
146
  set_field(f);
147
}
148
149
150
Item_field::Item_field(Name_resolution_context *context_arg,
151
                       const char *db_arg,const char *table_name_arg,
152
                       const char *field_name_arg)
153
  :Item_ident(context_arg, db_arg,table_name_arg,field_name_arg),
154
   field(0), result_field(0), item_equal(0), no_const_subst(0),
155
   have_privileges(0), any_privileges(0)
156
{
846 by Brian Aker
Removing on typedeffed class.
157
  Select_Lex *select= current_session->lex->current_select;
642.1.1 by Lee
move functions from item.cc/item.h to item directory
158
  collation.set(DERIVATION_IMPLICIT);
159
  if (select && select->parsing_place != IN_HAVING)
160
      select->select_n_where_fields++;
161
}
162
163
/**
164
  Constructor need to process subselect with temporary tables (see Item)
165
*/
166
167
Item_field::Item_field(Session *session, Item_field *item)
168
  :Item_ident(session, item),
169
   field(item->field),
170
   result_field(item->result_field),
171
   item_equal(item->item_equal),
172
   no_const_subst(item->no_const_subst),
173
   have_privileges(item->have_privileges),
174
   any_privileges(item->any_privileges)
175
{
176
  collation.set(DERIVATION_IMPLICIT);
177
}
178
179
void Item_field::set_field(Field *field_par)
180
{
181
  field=result_field=field_par;			// for easy coding with fields
182
  maybe_null=field->maybe_null();
183
  decimals= field->decimals();
184
  max_length= field_par->max_display_length();
185
  table_name= *field_par->table_name;
186
  field_name= field_par->field_name;
187
  db_name= field_par->table->s->db.str;
188
  alias_name_used= field_par->table->alias_name_used;
189
  unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
190
  collation.set(field_par->charset(), field_par->derivation());
191
  fixed= 1;
192
  if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
193
    any_privileges= 0;
194
}
195
196
197
/**
198
  Reset this item to point to a field from the new temporary table.
199
  This is used when we create a new temporary table for each execution
200
  of prepared statement.
201
*/
202
203
void Item_field::reset_field(Field *f)
204
{
205
  set_field(f);
206
  /* 'name' is pointing at field->field_name of old field */
207
  name= (char*) f->field_name;
208
}
209
210
/* ARGSUSED */
211
String *Item_field::val_str(String *str)
212
{
213
  assert(fixed == 1);
214
  if ((null_value=field->is_null()))
215
    return 0;
216
  str->set_charset(str_value.charset());
217
  return field->val_str(str,&str_value);
218
}
219
220
221
double Item_field::val_real()
222
{
223
  assert(fixed == 1);
224
  if ((null_value=field->is_null()))
225
    return 0.0;
226
  return field->val_real();
227
}
228
229
230
int64_t Item_field::val_int()
231
{
232
  assert(fixed == 1);
233
  if ((null_value=field->is_null()))
234
    return 0;
235
  return field->val_int();
236
}
237
238
239
my_decimal *Item_field::val_decimal(my_decimal *decimal_value)
240
{
241
  if ((null_value= field->is_null()))
242
    return 0;
243
  return field->val_decimal(decimal_value);
244
}
245
246
247
String *Item_field::str_result(String *str)
248
{
249
  if ((null_value=result_field->is_null()))
250
    return 0;
251
  str->set_charset(str_value.charset());
252
  return result_field->val_str(str,&str_value);
253
}
254
255
bool Item_field::get_date(DRIZZLE_TIME *ltime,uint32_t fuzzydate)
256
{
257
  if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
258
  {
259
    memset(ltime, 0, sizeof(*ltime));
260
    return 1;
261
  }
262
  return 0;
263
}
264
265
bool Item_field::get_date_result(DRIZZLE_TIME *ltime,uint32_t fuzzydate)
266
{
267
  if ((null_value=result_field->is_null()) ||
268
      result_field->get_date(ltime,fuzzydate))
269
  {
270
    memset(ltime, 0, sizeof(*ltime));
271
    return 1;
272
  }
273
  return 0;
274
}
275
276
bool Item_field::get_time(DRIZZLE_TIME *ltime)
277
{
278
  if ((null_value=field->is_null()) || field->get_time(ltime))
279
  {
280
    memset(ltime, 0, sizeof(*ltime));
281
    return 1;
282
  }
283
  return 0;
284
}
285
286
double Item_field::val_result()
287
{
288
  if ((null_value=result_field->is_null()))
289
    return 0.0;
290
  return result_field->val_real();
291
}
292
293
int64_t Item_field::val_int_result()
294
{
295
  if ((null_value=result_field->is_null()))
296
    return 0;
297
  return result_field->val_int();
298
}
299
300
301
my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value)
302
{
303
  if ((null_value= result_field->is_null()))
304
    return 0;
305
  return result_field->val_decimal(decimal_value);
306
}
307
308
309
bool Item_field::val_bool_result()
310
{
311
  if ((null_value= result_field->is_null()))
312
    return false;
313
  switch (result_field->result_type()) {
314
  case INT_RESULT:
315
    return result_field->val_int() != 0;
316
  case DECIMAL_RESULT:
317
  {
318
    my_decimal decimal_value;
319
    my_decimal *val= result_field->val_decimal(&decimal_value);
320
    if (val)
321
      return !my_decimal_is_zero(val);
322
    return 0;
323
  }
324
  case REAL_RESULT:
325
  case STRING_RESULT:
326
    return result_field->val_real() != 0.0;
327
  case ROW_RESULT:
328
  default:
329
    assert(0);
330
    return 0;                                   // Shut up compiler
331
  }
332
}
333
334
335
bool Item_field::eq(const Item *item, bool) const
336
{
779.3.10 by Monty Taylor
Turned on -Wshadow.
337
  const Item *item_ptr= item->real_item();
338
  if (item_ptr->type() != FIELD_ITEM)
642.1.1 by Lee
move functions from item.cc/item.h to item directory
339
    return 0;
340
779.3.10 by Monty Taylor
Turned on -Wshadow.
341
  const Item_field *item_field= static_cast<const Item_field *>(item_ptr);
642.1.1 by Lee
move functions from item.cc/item.h to item directory
342
  if (item_field->field && field)
343
    return item_field->field == field;
344
  /*
345
    We may come here when we are trying to find a function in a GROUP BY
346
    clause from the select list.
347
    In this case the '100 % correct' way to do this would be to first
348
    run fix_fields() on the GROUP BY item and then retry this function, but
349
    I think it's better to relax the checking a bit as we will in
350
    most cases do the correct thing by just checking the field name.
351
    (In cases where we would choose wrong we would have to generate a
352
    ER_NON_UNIQ_ERROR).
353
  */
354
  return (!my_strcasecmp(system_charset_info, item_field->name,
355
			 field_name) &&
356
	  (!item_field->table_name || !table_name ||
357
	   (!my_strcasecmp(table_alias_charset, item_field->table_name,
358
			   table_name) &&
359
	    (!item_field->db_name || !db_name ||
360
	     (item_field->db_name && !strcmp(item_field->db_name,
361
					     db_name))))));
362
}
363
364
365
table_map Item_field::used_tables() const
366
{
367
  if (field->table->const_table)
368
    return 0;					// const item
369
  return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
370
}
371
372
enum Item_result Item_field::result_type () const
373
{
374
  return field->result_type();
375
}
376
377
378
Item_result Item_field::cast_to_int_type() const
379
{
380
  return field->cast_to_int_type();
381
}
382
383
384
enum_field_types Item_field::field_type() const
385
{
386
  return field->type();
387
}
388
389
846 by Brian Aker
Removing on typedeffed class.
390
void Item_field::fix_after_pullout(Select_Lex *new_parent, Item **)
642.1.1 by Lee
move functions from item.cc/item.h to item directory
391
{
392
  if (new_parent == depended_from)
393
    depended_from= NULL;
394
  Name_resolution_context *ctx= new Name_resolution_context();
395
  ctx->outer_context= NULL; // We don't build a complete name resolver
396
  ctx->select_lex= new_parent;
397
  ctx->first_name_resolution_table= context->first_name_resolution_table;
398
  ctx->last_name_resolution_table=  context->last_name_resolution_table;
399
  this->context=ctx;
400
}
401
402
403
bool Item_field::is_null()
404
{
405
  return field->is_null();
406
}
407
408
409
Item *Item_field::get_tmp_table_item(Session *session)
410
{
411
  Item_field *new_item= new Item_field(session, this);
412
  if (new_item)
413
    new_item->field= new_item->result_field;
414
  return new_item;
415
}
416
417
int64_t Item_field::val_int_endpoint(bool, bool *)
418
{
419
  int64_t res= val_int();
420
  return null_value? INT64_MIN : res;
421
}
422
423
424
/**
425
  Resolve the name of an outer select column reference.
426
427
  The method resolves the column reference represented by 'this' as a column
428
  present in outer selects that contain current select.
429
430
  In prepared statements, because of cache, find_field_in_tables()
431
  can resolve fields even if they don't belong to current context.
432
  In this case this method only finds appropriate context and marks
433
  current select as dependent. The found reference of field should be
434
  provided in 'from_field'.
435
436
  @param[in] session             current thread
437
  @param[in,out] from_field  found field reference or (Field*)not_found_field
438
  @param[in,out] reference   view column if this item was resolved to a
439
    view column
440
441
  @note
442
    This is the inner loop of Item_field::fix_fields:
443
  @code
444
        for each outer query Q_k beginning from the inner-most one
445
        {
446
          search for a column or derived column named col_ref_i
447
          [in table T_j] in the FROM clause of Q_k;
448
449
          if such a column is not found
450
            Search for a column or derived column named col_ref_i
451
            [in table T_j] in the SELECT and GROUP clauses of Q_k.
452
        }
453
  @endcode
454
455
  @retval
456
    1   column succefully resolved and fix_fields() should continue.
457
  @retval
458
    0   column fully fixed and fix_fields() should return false
459
  @retval
460
    -1  error occured
461
*/
462
463
int
464
Item_field::fix_outer_field(Session *session, Field **from_field, Item **reference)
465
{
466
  enum_parsing_place place= NO_MATTER;
467
  bool field_found= (*from_field != not_found_field);
468
  bool upward_lookup= false;
469
470
  /*
471
    If there are outer contexts (outer selects, but current select is
472
    not derived table or view) try to resolve this reference in the
473
    outer contexts.
474
475
    We treat each subselect as a separate namespace, so that different
476
    subselects may contain columns with the same names. The subselects
477
    are searched starting from the innermost.
478
  */
479
  Name_resolution_context *last_checked_context= context;
480
  Item **ref= (Item **) not_found_item;
846 by Brian Aker
Removing on typedeffed class.
481
  Select_Lex *current_sel= (Select_Lex *) session->lex->current_select;
642.1.1 by Lee
move functions from item.cc/item.h to item directory
482
  Name_resolution_context *outer_context= 0;
846 by Brian Aker
Removing on typedeffed class.
483
  Select_Lex *select= 0;
642.1.1 by Lee
move functions from item.cc/item.h to item directory
484
  /* Currently derived tables cannot be correlated */
485
  if (current_sel->master_unit()->first_select()->linkage !=
486
      DERIVED_TABLE_TYPE)
487
    outer_context= context->outer_context;
488
  for (;
489
       outer_context;
490
       outer_context= outer_context->outer_context)
491
  {
492
    select= outer_context->select_lex;
493
    Item_subselect *prev_subselect_item=
494
      last_checked_context->select_lex->master_unit()->item;
495
    last_checked_context= outer_context;
496
    upward_lookup= true;
497
498
    place= prev_subselect_item->parsing_place;
499
    /*
500
      If outer_field is set, field was already found by first call
501
      to find_field_in_tables(). Only need to find appropriate context.
502
    */
503
    if (field_found && outer_context->select_lex !=
504
        cached_table->select_lex)
505
      continue;
506
    /*
507
      In case of a view, find_field_in_tables() writes the pointer to
508
      the found view field into '*reference', in other words, it
509
      substitutes this Item_field with the found expression.
510
    */
511
    if (field_found || (*from_field= find_field_in_tables(session, this,
512
                                          outer_context->
513
                                            first_name_resolution_table,
514
                                          outer_context->
515
                                            last_name_resolution_table,
516
                                          reference,
517
                                          IGNORE_EXCEPT_NON_UNIQUE,
518
                                          true, true)) !=
519
        not_found_field)
520
    {
521
      if (*from_field)
522
      {
523
        if (*from_field != view_ref_found)
524
        {
525
          prev_subselect_item->used_tables_cache|= (*from_field)->table->map;
526
          prev_subselect_item->const_item_cache= 0;
527
          set_field(*from_field);
528
          if (!last_checked_context->select_lex->having_fix_field &&
529
              select->group_list.elements &&
530
              (place == SELECT_LIST || place == IN_HAVING))
531
          {
532
            Item_outer_ref *rf;
533
            /*
534
              If an outer field is resolved in a grouping select then it
535
              is replaced for an Item_outer_ref object. Otherwise an
536
              Item_field object is used.
537
              The new Item_outer_ref object is saved in the inner_refs_list of
538
              the outer select. Here it is only created. It can be fixed only
539
              after the original field has been fixed and this is done in the
540
              fix_inner_refs() function.
541
            */
542
            ;
543
            if (!(rf= new Item_outer_ref(context, this)))
544
              return -1;
545
            session->change_item_tree(reference, rf);
546
            select->inner_refs_list.push_back(rf);
547
            rf->in_sum_func= session->lex->in_sum_func;
548
          }
549
          /*
550
            A reference is resolved to a nest level that's outer or the same as
551
            the nest level of the enclosing set function : adjust the value of
552
            max_arg_level for the function if it's needed.
553
          */
554
          if (session->lex->in_sum_func &&
555
              session->lex->in_sum_func->nest_level >= select->nest_level)
556
          {
557
            Item::Type ref_type= (*reference)->type();
558
            set_if_bigger(session->lex->in_sum_func->max_arg_level,
559
                          select->nest_level);
560
            set_field(*from_field);
561
            fixed= 1;
562
            mark_as_dependent(session, last_checked_context->select_lex,
563
                              context->select_lex, this,
564
                              ((ref_type == REF_ITEM ||
565
                                ref_type == FIELD_ITEM) ?
566
                               (Item_ident*) (*reference) : 0));
567
            return 0;
568
          }
569
        }
570
        else
571
        {
572
          Item::Type ref_type= (*reference)->type();
573
          prev_subselect_item->used_tables_cache|=
574
            (*reference)->used_tables();
575
          prev_subselect_item->const_item_cache&=
576
            (*reference)->const_item();
577
          mark_as_dependent(session, last_checked_context->select_lex,
578
                            context->select_lex, this,
579
                            ((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ?
580
                             (Item_ident*) (*reference) :
581
                             0));
582
          /*
583
            A reference to a view field had been found and we
584
            substituted it instead of this Item (find_field_in_tables
585
            does it by assigning the new value to *reference), so now
586
            we can return from this function.
587
          */
588
          return 0;
589
        }
590
      }
591
      break;
592
    }
593
594
    /* Search in SELECT and GROUP lists of the outer select. */
595
    if (place != IN_WHERE && place != IN_ON)
596
    {
597
      if (!(ref= resolve_ref_in_select_and_group(session, this, select)))
598
        return -1; /* Some error occurred (e.g. ambiguous names). */
599
      if (ref != not_found_item)
600
      {
601
        assert(*ref && (*ref)->fixed);
602
        prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
603
        prev_subselect_item->const_item_cache&= (*ref)->const_item();
604
        break;
605
      }
606
    }
607
608
    /*
609
      Reference is not found in this select => this subquery depend on
610
      outer select (or we just trying to find wrong identifier, in this
611
      case it does not matter which used tables bits we set)
612
    */
613
    prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
614
    prev_subselect_item->const_item_cache= 0;
615
  }
616
617
  assert(ref != 0);
618
  if (!*from_field)
619
    return -1;
620
  if (ref == not_found_item && *from_field == not_found_field)
621
  {
622
    if (upward_lookup)
623
    {
624
      // We can't say exactly what absent table or field
625
      my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), session->where);
626
    }
627
    else
628
    {
629
      /* Call find_field_in_tables only to report the error */
630
      find_field_in_tables(session, this,
631
                           context->first_name_resolution_table,
632
                           context->last_name_resolution_table,
633
                           reference, REPORT_ALL_ERRORS,
634
                           !any_privileges &&
635
                           true, true);
636
    }
637
    return -1;
638
  }
639
  else if (ref != not_found_item)
640
  {
641
    Item *save;
642
    Item_ref *rf;
643
644
    /* Should have been checked in resolve_ref_in_select_and_group(). */
645
    assert(*ref && (*ref)->fixed);
646
    /*
647
      Here, a subset of actions performed by Item_ref::set_properties
648
      is not enough. So we pass ptr to NULL into Item_[direct]_ref
660.1.6 by Eric Herman
trailing whitespace fixup
649
      constructor, so no initialization is performed, and call
642.1.1 by Lee
move functions from item.cc/item.h to item directory
650
      fix_fields() below.
651
    */
652
    save= *ref;
653
    *ref= NULL;                             // Don't call set_properties()
654
    rf= (place == IN_HAVING ?
655
         new Item_ref(context, ref, (char*) table_name,
656
                      (char*) field_name, alias_name_used) :
657
         (!select->group_list.elements ?
658
         new Item_direct_ref(context, ref, (char*) table_name,
659
                             (char*) field_name, alias_name_used) :
660
         new Item_outer_ref(context, ref, (char*) table_name,
661
                            (char*) field_name, alias_name_used)));
662
    *ref= save;
663
    if (!rf)
664
      return -1;
665
666
    if (place != IN_HAVING && select->group_list.elements)
667
    {
668
      outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf);
669
      ((Item_outer_ref*)rf)->in_sum_func= session->lex->in_sum_func;
670
    }
671
    session->change_item_tree(reference, rf);
672
    /*
673
      rf is Item_ref => never substitute other items (in this case)
674
      during fix_fields() => we can use rf after fix_fields()
675
    */
676
    assert(!rf->fixed);                // Assured by Item_ref()
677
    if (rf->fix_fields(session, reference) || rf->check_cols(1))
678
      return -1;
679
680
    mark_as_dependent(session, last_checked_context->select_lex,
681
                      context->select_lex, this,
682
                      rf);
683
    return 0;
684
  }
685
  else
686
  {
687
    mark_as_dependent(session, last_checked_context->select_lex,
688
                      context->select_lex,
689
                      this, (Item_ident*)*reference);
690
    if (last_checked_context->select_lex->having_fix_field)
691
    {
692
      Item_ref *rf;
693
      rf= new Item_ref(context,
694
                       (cached_table->db[0] ? cached_table->db : 0),
695
                       (char*) cached_table->alias, (char*) field_name);
696
      if (!rf)
697
        return -1;
698
      session->change_item_tree(reference, rf);
699
      /*
700
        rf is Item_ref => never substitute other items (in this case)
701
        during fix_fields() => we can use rf after fix_fields()
702
      */
703
      assert(!rf->fixed);                // Assured by Item_ref()
704
      if (rf->fix_fields(session, reference) || rf->check_cols(1))
705
        return -1;
706
      return 0;
707
    }
708
  }
709
  return 1;
710
}
711
712
713
/**
714
  Resolve the name of a column reference.
715
716
  The method resolves the column reference represented by 'this' as a column
717
  present in one of: FROM clause, SELECT clause, GROUP BY clause of a query
718
  Q, or in outer queries that contain Q.
719
720
  The name resolution algorithm used is (where [T_j] is an optional table
721
  name that qualifies the column name):
722
723
  @code
724
    resolve_column_reference([T_j].col_ref_i)
725
    {
726
      search for a column or derived column named col_ref_i
727
      [in table T_j] in the FROM clause of Q;
728
729
      if such a column is NOT found AND    // Lookup in outer queries.
730
         there are outer queries
731
      {
732
        for each outer query Q_k beginning from the inner-most one
733
        {
734
          search for a column or derived column named col_ref_i
735
          [in table T_j] in the FROM clause of Q_k;
736
737
          if such a column is not found
738
            Search for a column or derived column named col_ref_i
739
            [in table T_j] in the SELECT and GROUP clauses of Q_k.
740
        }
741
      }
742
    }
743
  @endcode
744
745
    Notice that compared to Item_ref::fix_fields, here we first search the FROM
746
    clause, and then we search the SELECT and GROUP BY clauses.
747
748
  @param[in]     session        current thread
749
  @param[in,out] reference  view column if this item was resolved to a
750
    view column
751
752
  @retval
753
    true  if error
754
  @retval
755
    false on success
756
*/
757
758
bool Item_field::fix_fields(Session *session, Item **reference)
759
{
760
  assert(fixed == 0);
761
  Field *from_field= (Field *)not_found_field;
762
  bool outer_fixed= false;
763
764
  if (!field)					// If field is not checked
765
  {
766
    /*
767
      In case of view, find_field_in_tables() write pointer to view field
768
      expression to 'reference', i.e. it substitute that expression instead
769
      of this Item_field
770
    */
771
    if ((from_field= find_field_in_tables(session, this,
772
                                          context->first_name_resolution_table,
773
                                          context->last_name_resolution_table,
774
                                          reference,
775
                                          session->lex->use_only_table_context ?
660.1.6 by Eric Herman
trailing whitespace fixup
776
                                            REPORT_ALL_ERRORS :
642.1.1 by Lee
move functions from item.cc/item.h to item directory
777
                                            IGNORE_EXCEPT_NON_UNIQUE,
778
                                          !any_privileges,
779
                                          true)) ==
780
	not_found_field)
781
    {
782
      int ret;
783
      /* Look up in current select's item_list to find aliased fields */
784
      if (session->lex->current_select->is_item_list_lookup)
785
      {
786
        uint32_t counter;
787
        enum_resolution_type resolution;
788
        Item** res= find_item_in_list(this, session->lex->current_select->item_list,
789
                                      &counter, REPORT_EXCEPT_NOT_FOUND,
790
                                      &resolution);
791
        if (!res)
792
          return 1;
793
        if (resolution == RESOLVED_AGAINST_ALIAS)
794
          alias_name_used= true;
795
        if (res != (Item **)not_found_item)
796
        {
797
          if ((*res)->type() == Item::FIELD_ITEM)
798
          {
799
            /*
800
              It's an Item_field referencing another Item_field in the select
801
              list.
802
              Use the field from the Item_field in the select list and leave
803
              the Item_field instance in place.
804
            */
805
806
            Field *new_field= (*((Item_field**)res))->field;
807
808
            if (new_field == NULL)
809
            {
810
              /* The column to which we link isn't valid. */
660.1.6 by Eric Herman
trailing whitespace fixup
811
              my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->name,
642.1.1 by Lee
move functions from item.cc/item.h to item directory
812
                       current_session->where);
813
              return(1);
814
            }
815
816
            set_field(new_field);
817
            return 0;
818
          }
819
          else
820
          {
821
            /*
822
              It's not an Item_field in the select list so we must make a new
823
              Item_ref to point to the Item in the select list and replace the
824
              Item_field created by the parser with the new Item_ref.
825
            */
826
            Item_ref *rf= new Item_ref(context, db_name,table_name,field_name);
827
            if (!rf)
828
              return 1;
829
            session->change_item_tree(reference, rf);
830
            /*
660.1.6 by Eric Herman
trailing whitespace fixup
831
              Because Item_ref never substitutes itself with other items
832
              in Item_ref::fix_fields(), we can safely use the original
642.1.1 by Lee
move functions from item.cc/item.h to item directory
833
              pointer to it even after fix_fields()
834
             */
835
            return rf->fix_fields(session, reference) ||  rf->check_cols(1);
836
          }
837
        }
838
      }
839
      if ((ret= fix_outer_field(session, &from_field, reference)) < 0)
840
        goto error;
841
      outer_fixed= true;
842
      if (!ret)
843
        goto mark_non_agg_field;
844
    }
845
    else if (!from_field)
846
      goto error;
847
848
    if (!outer_fixed && cached_table && cached_table->select_lex &&
849
        context->select_lex &&
850
        cached_table->select_lex != context->select_lex)
851
    {
852
      int ret;
853
      if ((ret= fix_outer_field(session, &from_field, reference)) < 0)
854
        goto error;
855
      outer_fixed= 1;
856
      if (!ret)
857
        goto mark_non_agg_field;
858
    }
859
860
    /*
861
      if it is not expression from merged VIEW we will set this field.
862
863
      We can leave expression substituted from view for next PS/SP rexecution
864
      (i.e. do not register this substitution for reverting on cleanup()
865
      (register_item_tree_changing())), because this subtree will be
866
      fix_field'ed during setup_tables()->setup_underlying() (i.e. before
867
      all other expressions of query, and references on tables which do
868
      not present in query will not make problems.
869
870
      Also we suppose that view can't be changed during PS/SP life.
871
    */
872
    if (from_field == view_ref_found)
873
      return false;
874
875
    set_field(from_field);
876
    if (session->lex->in_sum_func &&
660.1.6 by Eric Herman
trailing whitespace fixup
877
        session->lex->in_sum_func->nest_level ==
642.1.1 by Lee
move functions from item.cc/item.h to item directory
878
        session->lex->current_select->nest_level)
937.2.6 by Stewart Smith
make set_if_bigger typesafe for C and C++. Fix up everywhere.
879
    {
642.1.1 by Lee
move functions from item.cc/item.h to item directory
880
      set_if_bigger(session->lex->in_sum_func->max_arg_level,
881
                    session->lex->current_select->nest_level);
937.2.6 by Stewart Smith
make set_if_bigger typesafe for C and C++. Fix up everywhere.
882
    }
642.1.1 by Lee
move functions from item.cc/item.h to item directory
883
  }
884
  else if (session->mark_used_columns != MARK_COLUMNS_NONE)
885
  {
886
    Table *table= field->table;
1005.2.3 by Monty Taylor
Further reversion of P.
887
    MY_BITMAP *current_bitmap, *other_bitmap;
642.1.1 by Lee
move functions from item.cc/item.h to item directory
888
    if (session->mark_used_columns == MARK_COLUMNS_READ)
889
    {
890
      current_bitmap= table->read_set;
891
      other_bitmap=   table->write_set;
892
    }
893
    else
894
    {
895
      current_bitmap= table->write_set;
896
      other_bitmap=   table->read_set;
897
    }
1005.2.3 by Monty Taylor
Further reversion of P.
898
    if (!bitmap_fast_test_and_set(current_bitmap, field->field_index))
642.1.1 by Lee
move functions from item.cc/item.h to item directory
899
    {
1005.2.3 by Monty Taylor
Further reversion of P.
900
      if (!bitmap_is_set(other_bitmap, field->field_index))
642.1.1 by Lee
move functions from item.cc/item.h to item directory
901
      {
902
        /* First usage of column */
903
        table->used_fields++;                     // Used to optimize loops
904
        /* purecov: begin inspected */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
905
        table->covering_keys&= field->part_of_key;
642.1.1 by Lee
move functions from item.cc/item.h to item directory
906
        /* purecov: end */
907
      }
908
    }
909
  }
910
  fixed= 1;
911
mark_non_agg_field:
912
  return false;
913
914
error:
915
  context->process_error(session);
916
  return true;
917
}
918
919
Item *Item_field::safe_charset_converter(const CHARSET_INFO * const tocs)
920
{
921
  no_const_subst= 1;
922
  return Item::safe_charset_converter(tocs);
923
}
924
925
926
void Item_field::cleanup()
927
{
928
  Item_ident::cleanup();
929
  /*
930
    Even if this object was created by direct link to field in setup_wild()
931
    it will be linked correctly next time by name of field and table alias.
932
    I.e. we can drop 'field'.
933
   */
934
  field= result_field= 0;
935
  null_value= false;
936
  return;
937
}
938
939
940
bool Item_field::result_as_int64_t()
941
{
942
  return field->can_be_compared_as_int64_t();
943
}
944
945
946
/**
947
  Find a field among specified multiple equalities.
948
949
  The function first searches the field among multiple equalities
950
  of the current level (in the cond_equal->current_level list).
951
  If it fails, it continues searching in upper levels accessed
952
  through a pointer cond_equal->upper_levels.
660.1.6 by Eric Herman
trailing whitespace fixup
953
  The search terminates as soon as a multiple equality containing
954
  the field is found.
642.1.1 by Lee
move functions from item.cc/item.h to item directory
955
956
  @param cond_equal   reference to list of multiple equalities where
957
                      the field (this object) is to be looked for
958
959
  @return
960
    - First Item_equal containing the field, if success
961
    - 0, otherwise
962
*/
963
964
Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal)
965
{
966
  Item_equal *item= 0;
967
  while (cond_equal)
968
  {
969
    List_iterator_fast<Item_equal> li(cond_equal->current_level);
970
    while ((item= li++))
971
    {
972
      if (item->contains(field))
973
        return item;
974
    }
660.1.6 by Eric Herman
trailing whitespace fixup
975
    /*
642.1.1 by Lee
move functions from item.cc/item.h to item directory
976
      The field is not found in any of the multiple equalities
977
      of the current level. Look for it in upper levels
978
    */
979
    cond_equal= cond_equal->upper_levels;
980
  }
981
  return 0;
982
}
983
984
985
/**
986
  Check whether a field can be substituted by an equal item.
987
988
  The function checks whether a substitution of the field
989
  occurrence for an equal item is valid.
990
991
  @param arg   *arg != NULL <-> the field is in the context where
992
               substitution for an equal item is valid
993
994
  @note
995
    The following statement is not always true:
996
  @n
997
    x=y => F(x)=F(x/y).
998
  @n
999
    This means substitution of an item for an equal item not always
1000
    yields an equavalent condition. Here's an example:
1001
    @code
1002
    'a'='a '
1003
    (LENGTH('a')=1) != (LENGTH('a ')=2)
1004
  @endcode
1005
    Such a substitution is surely valid if either the substituted
1006
    field is not of a STRING type or if it is an argument of
1007
    a comparison predicate.
1008
1009
  @retval
1010
    true   substitution is valid
1011
  @retval
1012
    false  otherwise
1013
*/
1014
1015
bool Item_field::subst_argument_checker(unsigned char **arg)
1016
{
1017
  return (result_type() != STRING_RESULT) || (*arg);
1018
}
1019
1020
1021
/**
1022
  Set a pointer to the multiple equality the field reference belongs to
1023
  (if any).
1024
1025
  The function looks for a multiple equality containing the field item
1026
  among those referenced by arg.
1027
  In the case such equality exists the function does the following.
1028
  If the found multiple equality contains a constant, then the field
1029
  reference is substituted for this constant, otherwise it sets a pointer
1030
  to the multiple equality in the field item.
1031
1032
1033
  @param arg    reference to list of multiple equalities where
1034
                the field (this object) is to be looked for
1035
1036
  @note
1037
    This function is supposed to be called as a callback parameter in calls
1038
    of the compile method.
1039
1040
  @return
1041
    - pointer to the replacing constant item, if the field item was substituted
1042
    - pointer to the field item, otherwise.
1043
*/
1044
1045
Item *Item_field::equal_fields_propagator(unsigned char *arg)
1046
{
1047
  if (no_const_subst)
1048
    return this;
1049
  item_equal= find_item_equal((COND_EQUAL *) arg);
1050
  Item *item= 0;
1051
  if (item_equal)
1052
    item= item_equal->get_const();
1053
  /*
1054
    Disable const propagation for items used in different comparison contexts.
1055
    This must be done because, for example, Item_hex_string->val_int() is not
1056
    the same as (Item_hex_string->val_str() in BINARY column)->val_int().
1057
    We cannot simply disable the replacement in a particular context (
1058
    e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
660.1.6 by Eric Herman
trailing whitespace fixup
1059
    Items don't know the context they are in and there are functions like
642.1.1 by Lee
move functions from item.cc/item.h to item directory
1060
    IF (<hex_string>, 'yes', 'no').
1061
    The same problem occurs when comparing a DATE/TIME field with a
1062
    DATE/TIME represented as an int and as a string.
1063
  */
1064
  if (!item ||
1065
      (cmp_context != (Item_result)-1 && item->cmp_context != cmp_context))
1066
    item= this;
1067
1068
  return item;
1069
}
1070
1071
1072
/**
1073
  Mark the item to not be part of substitution if it's not a binary item.
1074
1075
  See comments in Arg_comparator::set_compare_func() for details.
1076
*/
1077
1078
bool Item_field::set_no_const_sub(unsigned char *)
1079
{
1080
  if (field->charset() != &my_charset_bin)
1081
    no_const_subst=1;
1082
  return false;
1083
}
1084
1085
1086
/**
1087
  Replace an Item_field for an equal Item_field that evaluated earlier
1088
  (if any).
1089
1090
  The function returns a pointer to an item that is taken from
1091
  the very beginning of the item_equal list which the Item_field
1092
  object refers to (belongs to) unless item_equal contains  a constant
660.1.6 by Eric Herman
trailing whitespace fixup
1093
  item. In this case the function returns this constant item,
1094
  (if the substitution does not require conversion).
642.1.1 by Lee
move functions from item.cc/item.h to item directory
1095
  If the Item_field object does not refer any Item_equal object
1096
  'this' is returned .
1097
1098
  @param arg   a dummy parameter, is not used here
1099
1100
1101
  @note
1102
    This function is supposed to be called as a callback parameter in calls
1103
    of the thransformer method.
1104
1105
  @return
1106
    - pointer to a replacement Item_field if there is a better equal item or
1107
      a pointer to a constant equal item;
1108
    - this - otherwise.
1109
*/
1110
1111
Item *Item_field::replace_equal_field(unsigned char *)
1112
{
1113
  if (item_equal)
1114
  {
779.3.10 by Monty Taylor
Turned on -Wshadow.
1115
    Item *const_item_ptr= item_equal->get_const();
1116
    if (const_item_ptr)
642.1.1 by Lee
move functions from item.cc/item.h to item directory
1117
    {
1118
      if (cmp_context != (Item_result)-1 &&
779.3.10 by Monty Taylor
Turned on -Wshadow.
1119
          const_item_ptr->cmp_context != cmp_context)
642.1.1 by Lee
move functions from item.cc/item.h to item directory
1120
        return this;
779.3.10 by Monty Taylor
Turned on -Wshadow.
1121
      return const_item_ptr;
642.1.1 by Lee
move functions from item.cc/item.h to item directory
1122
    }
1123
    Item_field *subst= item_equal->get_first();
1124
    if (subst && !field->eq(subst->field))
1125
      return subst;
1126
  }
1127
  return this;
1128
}
1129
1130
1131
uint32_t Item_field::max_disp_length()
1132
{
1133
  return field->max_display_length();
1134
}
1135
1136
1137
/* ARGSUSED */
1138
void Item_field::make_field(Send_field *tmp_field)
1139
{
1140
  field->make_field(tmp_field);
1141
  assert(tmp_field->table_name != 0);
1142
  if (name)
1143
    tmp_field->col_name=name;			// Use user supplied name
1144
  if (table_name)
1145
    tmp_field->table_name= table_name;
1146
  if (db_name)
1147
    tmp_field->db_name= db_name;
1148
}
1149
1150
1151
/**
1152
  Set a field's value from a item.
1153
*/
1154
1155
void Item_field::save_org_in_field(Field *to)
1156
{
1157
  if (field->is_null())
1158
  {
1159
    null_value=1;
1160
    set_field_to_null_with_conversions(to, 1);
1161
  }
1162
  else
1163
  {
1164
    to->set_notnull();
1165
    field_conv(to,field);
1166
    null_value=0;
1167
  }
1168
}
1169
1170
int Item_field::save_in_field(Field *to, bool no_conversions)
1171
{
1172
  int res;
1173
  if (result_field->is_null())
1174
  {
1175
    null_value=1;
1176
    res= set_field_to_null_with_conversions(to, no_conversions);
1177
  }
1178
  else
1179
  {
1180
    to->set_notnull();
1181
    res= field_conv(to,result_field);
1182
    null_value=0;
1183
  }
1184
  return(res);
1185
}
1186
1187
1188
bool Item_field::send(Protocol *protocol, String *)
1189
{
1190
  return protocol->store(result_field);
1191
}
1192
1193
1194
void Item_field::update_null_value()
1195
{
1196
  /*
1197
    need to set no_errors to prevent warnings about type conversion
1198
    popping up.
1199
  */
1200
  Session *session= field->table->in_use;
1201
  int no_errors;
1202
1203
  no_errors= session->no_errors;
1204
  session->no_errors= 1;
1205
  Item::update_null_value();
1206
  session->no_errors= no_errors;
1207
}
1208
1209
1210
/*
1211
  Add the field to the select list and substitute it for the reference to
1212
  the field.
1213
1214
  SYNOPSIS
1215
    Item_field::update_value_transformer()
1216
    select_arg      current select
1217
1218
  DESCRIPTION
1219
    If the field doesn't belong to the table being inserted into then it is
1220
    added to the select list, pointer to it is stored in the ref_pointer_array
1221
    of the select and the field itself is substituted for the Item_ref object.
1222
    This is done in order to get correct values from update fields that
1223
    belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY
1224
    UPDATE statement.
1225
1226
  RETURN
1227
    0             if error occured
1228
    ref           if all conditions are met
1229
    this field    otherwise
1230
*/
1231
1232
Item *Item_field::update_value_transformer(unsigned char *select_arg)
1233
{
846 by Brian Aker
Removing on typedeffed class.
1234
  Select_Lex *select= (Select_Lex*)select_arg;
642.1.1 by Lee
move functions from item.cc/item.h to item directory
1235
  assert(fixed);
1236
1237
  if (field->table != select->context.table_list->table)
1238
  {
1239
    List<Item> *all_fields= &select->join->all_fields;
1240
    Item **ref_pointer_array= select->ref_pointer_array;
1241
    int el= all_fields->elements;
1242
    Item_ref *ref;
1243
1244
    ref_pointer_array[el]= (Item*)this;
1245
    all_fields->push_front((Item*)this);
1246
    ref= new Item_ref(&select->context, ref_pointer_array + el,
1247
                      table_name, field_name);
1248
    return ref;
1249
  }
1250
  return this;
1251
}
1252
1253
1254
void Item_field::print(String *str, enum_query_type query_type)
1255
{
1256
  if (field && field->table->const_table)
1257
  {
1258
    char buff[MAX_FIELD_WIDTH];
1259
    String tmp(buff,sizeof(buff),str->charset());
1260
    field->val_str(&tmp);
1261
    str->append('\'');
1262
    str->append(tmp);
1263
    str->append('\'');
1264
    return;
1265
  }
1266
  Item_ident::print(str, query_type);
1267
}