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