~stewart/drizzle/embedded-innodb-create-select-transaction-arrgh

« back to all changes in this revision

Viewing changes to sql/item_cmpfunc.cc

  • Committer: brian
  • Date: 2008-06-25 05:29:13 UTC
  • Revision ID: brian@localhost.localdomain-20080625052913-6upwo0jsrl4lnapl
clean slate

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Copyright (C) 2000-2006 MySQL AB
 
2
 
 
3
   This program is free software; you can redistribute it and/or modify
 
4
   it under the terms of the GNU General Public License as published by
 
5
   the Free Software Foundation; version 2 of the License.
 
6
 
 
7
   This program is distributed in the hope that it will be useful,
 
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
   GNU General Public License for more details.
 
11
 
 
12
   You should have received a copy of the GNU General Public License
 
13
   along with this program; if not, write to the Free Software
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
15
 
 
16
 
 
17
/**
 
18
  @file
 
19
 
 
20
  @brief
 
21
  This file defines all compare functions
 
22
*/
 
23
 
 
24
#ifdef USE_PRAGMA_IMPLEMENTATION
 
25
#pragma implementation                          // gcc: Class implementation
 
26
#endif
 
27
 
 
28
#include "mysql_priv.h"
 
29
#include <m_ctype.h>
 
30
#include "sql_select.h"
 
31
 
 
32
static bool convert_constant_item(THD *, Item_field *, Item **);
 
33
 
 
34
static Item_result item_store_type(Item_result a, Item *item,
 
35
                                   my_bool unsigned_flag)
 
36
{
 
37
  Item_result b= item->result_type();
 
38
 
 
39
  if (a == STRING_RESULT || b == STRING_RESULT)
 
40
    return STRING_RESULT;
 
41
  else if (a == REAL_RESULT || b == REAL_RESULT)
 
42
    return REAL_RESULT;
 
43
  else if (a == DECIMAL_RESULT || b == DECIMAL_RESULT ||
 
44
           unsigned_flag != item->unsigned_flag)
 
45
    return DECIMAL_RESULT;
 
46
  else
 
47
    return INT_RESULT;
 
48
}
 
49
 
 
50
static void agg_result_type(Item_result *type, Item **items, uint nitems)
 
51
{
 
52
  Item **item, **item_end;
 
53
  my_bool unsigned_flag= 0;
 
54
 
 
55
  *type= STRING_RESULT;
 
56
  /* Skip beginning NULL items */
 
57
  for (item= items, item_end= item + nitems; item < item_end; item++)
 
58
  {
 
59
    if ((*item)->type() != Item::NULL_ITEM)
 
60
    {
 
61
      *type= (*item)->result_type();
 
62
      unsigned_flag= (*item)->unsigned_flag;
 
63
      item++;
 
64
      break;
 
65
    }
 
66
  }
 
67
  /* Combine result types. Note: NULL items don't affect the result */
 
68
  for (; item < item_end; item++)
 
69
  {
 
70
    if ((*item)->type() != Item::NULL_ITEM)
 
71
      *type= item_store_type(*type, *item, unsigned_flag);
 
72
  }
 
73
}
 
74
 
 
75
 
 
76
/*
 
77
  Compare row signature of two expressions
 
78
 
 
79
  SYNOPSIS:
 
80
    cmp_row_type()
 
81
    item1          the first expression
 
82
    item2         the second expression
 
83
 
 
84
  DESCRIPTION
 
85
    The function checks that two expressions have compatible row signatures
 
86
    i.e. that the number of columns they return are the same and that if they
 
87
    are both row expressions then each component from the first expression has 
 
88
    a row signature compatible with the signature of the corresponding component
 
89
    of the second expression.
 
90
 
 
91
  RETURN VALUES
 
92
    1  type incompatibility has been detected
 
93
    0  otherwise
 
94
*/
 
95
 
 
96
static int cmp_row_type(Item* item1, Item* item2)
 
97
{
 
98
  uint n= item1->cols();
 
99
  if (item2->check_cols(n))
 
100
    return 1;
 
101
  for (uint i=0; i<n; i++)
 
102
  {
 
103
    if (item2->element_index(i)->check_cols(item1->element_index(i)->cols()) ||
 
104
        (item1->element_index(i)->result_type() == ROW_RESULT &&
 
105
         cmp_row_type(item1->element_index(i), item2->element_index(i))))
 
106
      return 1;
 
107
  }
 
108
  return 0;
 
109
}
 
110
 
 
111
 
 
112
/**
 
113
  Aggregates result types from the array of items.
 
114
 
 
115
  SYNOPSIS:
 
116
    agg_cmp_type()
 
117
    type   [out] the aggregated type
 
118
    items        array of items to aggregate the type from
 
119
    nitems       number of items in the array
 
120
 
 
121
  DESCRIPTION
 
122
    This function aggregates result types from the array of items. Found type
 
123
    supposed to be used later for comparison of values of these items.
 
124
    Aggregation itself is performed by the item_cmp_type() function.
 
125
  @param[out] type    the aggregated type
 
126
  @param      items        array of items to aggregate the type from
 
127
  @param      nitems       number of items in the array
 
128
 
 
129
  @retval
 
130
    1  type incompatibility has been detected
 
131
  @retval
 
132
    0  otherwise
 
133
*/
 
134
 
 
135
static int agg_cmp_type(Item_result *type, Item **items, uint nitems)
 
136
{
 
137
  uint i;
 
138
  type[0]= items[0]->result_type();
 
139
  for (i= 1 ; i < nitems ; i++)
 
140
  {
 
141
    type[0]= item_cmp_type(type[0], items[i]->result_type());
 
142
    /*
 
143
      When aggregating types of two row expressions we have to check
 
144
      that they have the same cardinality and that each component
 
145
      of the first row expression has a compatible row signature with
 
146
      the signature of the corresponding component of the second row
 
147
      expression.
 
148
    */ 
 
149
    if (type[0] == ROW_RESULT && cmp_row_type(items[0], items[i]))
 
150
      return 1;     // error found: invalid usage of rows
 
151
  }
 
152
  return 0;
 
153
}
 
154
 
 
155
 
 
156
/**
 
157
  @brief Aggregates field types from the array of items.
 
158
 
 
159
  @param[in] items  array of items to aggregate the type from
 
160
  @paran[in] nitems number of items in the array
 
161
 
 
162
  @details This function aggregates field types from the array of items.
 
163
    Found type is supposed to be used later as the result field type
 
164
    of a multi-argument function.
 
165
    Aggregation itself is performed by the Field::field_type_merge()
 
166
    function.
 
167
 
 
168
  @note The term "aggregation" is used here in the sense of inferring the
 
169
    result type of a function from its argument types.
 
170
 
 
171
  @return aggregated field type.
 
172
*/
 
173
 
 
174
enum_field_types agg_field_type(Item **items, uint nitems)
 
175
{
 
176
  uint i;
 
177
  if (!nitems || items[0]->result_type() == ROW_RESULT )
 
178
    return (enum_field_types)-1;
 
179
  enum_field_types res= items[0]->field_type();
 
180
  for (i= 1 ; i < nitems ; i++)
 
181
    res= Field::field_type_merge(res, items[i]->field_type());
 
182
  return res;
 
183
}
 
184
 
 
185
/*
 
186
  Collects different types for comparison of first item with each other items
 
187
 
 
188
  SYNOPSIS
 
189
    collect_cmp_types()
 
190
      items             Array of items to collect types from
 
191
      nitems            Number of items in the array
 
192
 
 
193
  DESCRIPTION
 
194
    This function collects different result types for comparison of the first
 
195
    item in the list with each of the remaining items in the 'items' array.
 
196
 
 
197
  RETURN
 
198
    0 - if row type incompatibility has been detected (see cmp_row_type)
 
199
    Bitmap of collected types - otherwise
 
200
*/
 
201
 
 
202
static uint collect_cmp_types(Item **items, uint nitems)
 
203
{
 
204
  uint i;
 
205
  uint found_types;
 
206
  Item_result left_result= items[0]->result_type();
 
207
  DBUG_ASSERT(nitems > 1);
 
208
  found_types= 0;
 
209
  for (i= 1; i < nitems ; i++)
 
210
  {
 
211
    if ((left_result == ROW_RESULT || 
 
212
         items[i]->result_type() == ROW_RESULT) &&
 
213
        cmp_row_type(items[0], items[i]))
 
214
      return 0;
 
215
    found_types|= 1<< (uint)item_cmp_type(left_result,
 
216
                                           items[i]->result_type());
 
217
  }
 
218
  return found_types;
 
219
}
 
220
 
 
221
static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
 
222
                              const char *fname)
 
223
{
 
224
  my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
 
225
           c1.collation->name,c1.derivation_name(),
 
226
           c2.collation->name,c2.derivation_name(),
 
227
           fname);
 
228
}
 
229
 
 
230
 
 
231
Item_bool_func2* Eq_creator::create(Item *a, Item *b) const
 
232
{
 
233
  return new Item_func_eq(a, b);
 
234
}
 
235
 
 
236
 
 
237
Item_bool_func2* Ne_creator::create(Item *a, Item *b) const
 
238
{
 
239
  return new Item_func_ne(a, b);
 
240
}
 
241
 
 
242
 
 
243
Item_bool_func2* Gt_creator::create(Item *a, Item *b) const
 
244
{
 
245
  return new Item_func_gt(a, b);
 
246
}
 
247
 
 
248
 
 
249
Item_bool_func2* Lt_creator::create(Item *a, Item *b) const
 
250
{
 
251
  return new Item_func_lt(a, b);
 
252
}
 
253
 
 
254
 
 
255
Item_bool_func2* Ge_creator::create(Item *a, Item *b) const
 
256
{
 
257
  return new Item_func_ge(a, b);
 
258
}
 
259
 
 
260
 
 
261
Item_bool_func2* Le_creator::create(Item *a, Item *b) const
 
262
{
 
263
  return new Item_func_le(a, b);
 
264
}
 
265
 
 
266
/*
 
267
  Test functions
 
268
  Most of these  returns 0LL if false and 1LL if true and
 
269
  NULL if some arg is NULL.
 
270
*/
 
271
 
 
272
longlong Item_func_not::val_int()
 
273
{
 
274
  DBUG_ASSERT(fixed == 1);
 
275
  bool value= args[0]->val_bool();
 
276
  null_value=args[0]->null_value;
 
277
  return ((!null_value && value == 0) ? 1 : 0);
 
278
}
 
279
 
 
280
/*
 
281
  We put any NOT expression into parenthesis to avoid
 
282
  possible problems with internal view representations where
 
283
  any '!' is converted to NOT. It may cause a problem if
 
284
  '!' is used in an expression together with other operators
 
285
  whose precedence is lower than the precedence of '!' yet
 
286
  higher than the precedence of NOT.
 
287
*/
 
288
 
 
289
void Item_func_not::print(String *str, enum_query_type query_type)
 
290
{
 
291
  str->append('(');
 
292
  Item_func::print(str, query_type);
 
293
  str->append(')');
 
294
}
 
295
 
 
296
/**
 
297
  special NOT for ALL subquery.
 
298
*/
 
299
 
 
300
 
 
301
longlong Item_func_not_all::val_int()
 
302
{
 
303
  DBUG_ASSERT(fixed == 1);
 
304
  bool value= args[0]->val_bool();
 
305
 
 
306
  /*
 
307
    return TRUE if there was records in underlying select in max/min
 
308
    optimization (ALL subquery)
 
309
  */
 
310
  if (empty_underlying_subquery())
 
311
    return 1;
 
312
 
 
313
  null_value= args[0]->null_value;
 
314
  return ((!null_value && value == 0) ? 1 : 0);
 
315
}
 
316
 
 
317
 
 
318
bool Item_func_not_all::empty_underlying_subquery()
 
319
{
 
320
  return ((test_sum_item && !test_sum_item->any_value()) ||
 
321
          (test_sub_item && !test_sub_item->any_value()));
 
322
}
 
323
 
 
324
void Item_func_not_all::print(String *str, enum_query_type query_type)
 
325
{
 
326
  if (show)
 
327
    Item_func::print(str, query_type);
 
328
  else
 
329
    args[0]->print(str, query_type);
 
330
}
 
331
 
 
332
 
 
333
/**
 
334
  Special NOP (No OPeration) for ALL subquery. It is like
 
335
  Item_func_not_all.
 
336
 
 
337
  @return
 
338
    (return TRUE if underlying subquery do not return rows) but if subquery
 
339
    returns some rows it return same value as argument (TRUE/FALSE).
 
340
*/
 
341
 
 
342
longlong Item_func_nop_all::val_int()
 
343
{
 
344
  DBUG_ASSERT(fixed == 1);
 
345
  longlong value= args[0]->val_int();
 
346
 
 
347
  /*
 
348
    return FALSE if there was records in underlying select in max/min
 
349
    optimization (SAME/ANY subquery)
 
350
  */
 
351
  if (empty_underlying_subquery())
 
352
    return 0;
 
353
 
 
354
  null_value= args[0]->null_value;
 
355
  return (null_value || value == 0) ? 0 : 1;
 
356
}
 
357
 
 
358
 
 
359
/**
 
360
  Convert a constant item to an int and replace the original item.
 
361
 
 
362
    The function converts a constant expression or string to an integer.
 
363
    On successful conversion the original item is substituted for the
 
364
    result of the item evaluation.
 
365
    This is done when comparing DATE/TIME of different formats and
 
366
    also when comparing bigint to strings (in which case strings
 
367
    are converted to bigints).
 
368
 
 
369
  @param  thd             thread handle
 
370
  @param  field_item      item will be converted using the type of this field
 
371
  @param[in,out] item     reference to the item to convert
 
372
 
 
373
  @note
 
374
    This function is called only at prepare stage.
 
375
    As all derived tables are filled only after all derived tables
 
376
    are prepared we do not evaluate items with subselects here because
 
377
    they can contain derived tables and thus we may attempt to use a
 
378
    table that has not been populated yet.
 
379
 
 
380
  @retval
 
381
    0  Can't convert item
 
382
  @retval
 
383
    1  Item was replaced with an integer version of the item
 
384
*/
 
385
 
 
386
static bool convert_constant_item(THD *thd, Item_field *field_item,
 
387
                                  Item **item)
 
388
{
 
389
  Field *field= field_item->field;
 
390
  int result= 0;
 
391
 
 
392
  if (!(*item)->with_subselect && (*item)->const_item())
 
393
  {
 
394
    TABLE *table= field->table;
 
395
    ulong orig_sql_mode= thd->variables.sql_mode;
 
396
    enum_check_fields orig_count_cuted_fields= thd->count_cuted_fields;
 
397
    my_bitmap_map *old_write_map;
 
398
    my_bitmap_map *old_read_map;
 
399
    ulonglong orig_field_val= 0; /* original field value if valid */
 
400
 
 
401
    if (table)
 
402
    {
 
403
      old_write_map= dbug_tmp_use_all_columns(table, table->write_set);
 
404
      old_read_map= dbug_tmp_use_all_columns(table, table->read_set);
 
405
    }
 
406
    /* For comparison purposes allow invalid dates like 2000-01-32 */
 
407
    thd->variables.sql_mode= (orig_sql_mode & ~MODE_NO_ZERO_DATE) | 
 
408
                             MODE_INVALID_DATES;
 
409
    thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
410
 
 
411
    /*
 
412
      Store the value of the field if it references an outer field because
 
413
      the call to save_in_field below overrides that value.
 
414
    */
 
415
    if (field_item->depended_from)
 
416
      orig_field_val= field->val_int();
 
417
    if (!(*item)->is_null() && !(*item)->save_in_field(field, 1))
 
418
    {
 
419
      Item *tmp= new Item_int_with_ref(field->val_int(), *item,
 
420
                                       test(field->flags & UNSIGNED_FLAG));
 
421
      if (tmp)
 
422
        thd->change_item_tree(item, tmp);
 
423
      result= 1;                                        // Item was replaced
 
424
    }
 
425
    /* Restore the original field value. */
 
426
    if (field_item->depended_from)
 
427
    {
 
428
      result= field->store(orig_field_val, TRUE);
 
429
      /* orig_field_val must be a valid value that can be restored back. */
 
430
      DBUG_ASSERT(!result);
 
431
    }
 
432
    thd->variables.sql_mode= orig_sql_mode;
 
433
    thd->count_cuted_fields= orig_count_cuted_fields;
 
434
    if (table)
 
435
    {
 
436
      dbug_tmp_restore_column_map(table->write_set, old_write_map);
 
437
      dbug_tmp_restore_column_map(table->read_set, old_read_map);
 
438
    }
 
439
  }
 
440
  return result;
 
441
}
 
442
 
 
443
 
 
444
void Item_bool_func2::fix_length_and_dec()
 
445
{
 
446
  max_length= 1;                                     // Function returns 0 or 1
 
447
  THD *thd;
 
448
 
 
449
  /*
 
450
    As some compare functions are generated after sql_yacc,
 
451
    we have to check for out of memory conditions here
 
452
  */
 
453
  if (!args[0] || !args[1])
 
454
    return;
 
455
 
 
456
  /* 
 
457
    We allow to convert to Unicode character sets in some cases.
 
458
    The conditions when conversion is possible are:
 
459
    - arguments A and B have different charsets
 
460
    - A wins according to coercibility rules
 
461
    - character set of A is superset for character set of B
 
462
   
 
463
    If all of the above is true, then it's possible to convert
 
464
    B into the character set of A, and then compare according
 
465
    to the collation of A.
 
466
  */
 
467
 
 
468
  
 
469
  DTCollation coll;
 
470
  if (args[0]->result_type() == STRING_RESULT &&
 
471
      args[1]->result_type() == STRING_RESULT &&
 
472
      agg_arg_charsets(coll, args, 2, MY_COLL_CMP_CONV, 1))
 
473
    return;
 
474
    
 
475
  args[0]->cmp_context= args[1]->cmp_context=
 
476
    item_cmp_type(args[0]->result_type(), args[1]->result_type());
 
477
  // Make a special case of compare with fields to get nicer DATE comparisons
 
478
 
 
479
  if (functype() == LIKE_FUNC)  // Disable conversion in case of LIKE function.
 
480
  {
 
481
    set_cmp_func();
 
482
    return;
 
483
  }
 
484
 
 
485
  thd= current_thd;
 
486
  if (!thd->is_context_analysis_only())
 
487
  {
 
488
    if (args[0]->real_item()->type() == FIELD_ITEM)
 
489
    {
 
490
      Item_field *field_item= (Item_field*) (args[0]->real_item());
 
491
      if (field_item->field->can_be_compared_as_longlong() &&
 
492
          !(field_item->is_datetime() &&
 
493
            args[1]->result_type() == STRING_RESULT))
 
494
      {
 
495
        if (convert_constant_item(thd, field_item, &args[1]))
 
496
        {
 
497
          cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
 
498
                           INT_RESULT);         // Works for all types.
 
499
          args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
 
500
          return;
 
501
        }
 
502
      }
 
503
    }
 
504
    if (args[1]->real_item()->type() == FIELD_ITEM)
 
505
    {
 
506
      Item_field *field_item= (Item_field*) (args[1]->real_item());
 
507
      if (field_item->field->can_be_compared_as_longlong() &&
 
508
          !(field_item->is_datetime() &&
 
509
            args[0]->result_type() == STRING_RESULT))
 
510
      {
 
511
        if (convert_constant_item(thd, field_item, &args[0]))
 
512
        {
 
513
          cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
 
514
                           INT_RESULT); // Works for all types.
 
515
          args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
 
516
          return;
 
517
        }
 
518
      }
 
519
    }
 
520
  }
 
521
  set_cmp_func();
 
522
}
 
523
 
 
524
 
 
525
int Arg_comparator::set_compare_func(Item_bool_func2 *item, Item_result type)
 
526
{
 
527
  owner= item;
 
528
  func= comparator_matrix[type]
 
529
                         [test(owner->functype() == Item_func::EQUAL_FUNC)];
 
530
  switch (type) {
 
531
  case ROW_RESULT:
 
532
  {
 
533
    uint n= (*a)->cols();
 
534
    if (n != (*b)->cols())
 
535
    {
 
536
      my_error(ER_OPERAND_COLUMNS, MYF(0), n);
 
537
      comparators= 0;
 
538
      return 1;
 
539
    }
 
540
    if (!(comparators= new Arg_comparator[n]))
 
541
      return 1;
 
542
    for (uint i=0; i < n; i++)
 
543
    {
 
544
      if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols())
 
545
      {
 
546
        my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
 
547
        return 1;
 
548
      }
 
549
      comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i));
 
550
    }
 
551
    break;
 
552
  }
 
553
  case STRING_RESULT:
 
554
  {
 
555
    /*
 
556
      We must set cmp_charset here as we may be called from for an automatic
 
557
      generated item, like in natural join
 
558
    */
 
559
    if (cmp_collation.set((*a)->collation, (*b)->collation) || 
 
560
        cmp_collation.derivation == DERIVATION_NONE)
 
561
    {
 
562
      my_coll_agg_error((*a)->collation, (*b)->collation, owner->func_name());
 
563
      return 1;
 
564
    }
 
565
    if (cmp_collation.collation == &my_charset_bin)
 
566
    {
 
567
      /*
 
568
        We are using BLOB/BINARY/VARBINARY, change to compare byte by byte,
 
569
        without removing end space
 
570
      */
 
571
      if (func == &Arg_comparator::compare_string)
 
572
        func= &Arg_comparator::compare_binary_string;
 
573
      else if (func == &Arg_comparator::compare_e_string)
 
574
        func= &Arg_comparator::compare_e_binary_string;
 
575
 
 
576
      /*
 
577
        As this is binary compassion, mark all fields that they can't be
 
578
        transformed. Otherwise we would get into trouble with comparisons
 
579
        like:
 
580
        WHERE col= 'j' AND col LIKE BINARY 'j'
 
581
        which would be transformed to:
 
582
        WHERE col= 'j'
 
583
      */
 
584
      (*a)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0);
 
585
      (*b)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0);
 
586
    }
 
587
    break;
 
588
  }
 
589
  case INT_RESULT:
 
590
  {
 
591
    if (func == &Arg_comparator::compare_int_signed)
 
592
    {
 
593
      if ((*a)->unsigned_flag)
 
594
        func= (((*b)->unsigned_flag)?
 
595
               &Arg_comparator::compare_int_unsigned :
 
596
               &Arg_comparator::compare_int_unsigned_signed);
 
597
      else if ((*b)->unsigned_flag)
 
598
        func= &Arg_comparator::compare_int_signed_unsigned;
 
599
    }
 
600
    else if (func== &Arg_comparator::compare_e_int)
 
601
    {
 
602
      if ((*a)->unsigned_flag ^ (*b)->unsigned_flag)
 
603
        func= &Arg_comparator::compare_e_int_diff_signedness;
 
604
    }
 
605
    break;
 
606
  }
 
607
  case DECIMAL_RESULT:
 
608
    break;
 
609
  case REAL_RESULT:
 
610
  {
 
611
    if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC)
 
612
    {
 
613
      precision= 5 / log_10[max((*a)->decimals, (*b)->decimals) + 1];
 
614
      if (func == &Arg_comparator::compare_real)
 
615
        func= &Arg_comparator::compare_real_fixed;
 
616
      else if (func == &Arg_comparator::compare_e_real)
 
617
        func= &Arg_comparator::compare_e_real_fixed;
 
618
    }
 
619
    break;
 
620
  }
 
621
  default:
 
622
    DBUG_ASSERT(0);
 
623
  }
 
624
  return 0;
 
625
}
 
626
 
 
627
 
 
628
/**
 
629
  @brief Convert date provided in a string to the int representation.
 
630
 
 
631
  @param[in]   thd        thread handle
 
632
  @param[in]   str        a string to convert
 
633
  @param[in]   warn_type  type of the timestamp for issuing the warning
 
634
  @param[in]   warn_name  field name for issuing the warning
 
635
  @param[out]  error_arg  could not extract a DATE or DATETIME
 
636
 
 
637
  @details Convert date provided in the string str to the int
 
638
    representation.  If the string contains wrong date or doesn't
 
639
    contain it at all then a warning is issued.  The warn_type and
 
640
    the warn_name arguments are used as the name and the type of the
 
641
    field when issuing the warning.  If any input was discarded
 
642
    (trailing or non-timestampy characters), was_cut will be non-zero.
 
643
    was_type will return the type str_to_datetime() could correctly
 
644
    extract.
 
645
 
 
646
  @return
 
647
    converted value. 0 on error and on zero-dates -- check 'failure'
 
648
*/
 
649
 
 
650
static ulonglong
 
651
get_date_from_str(THD *thd, String *str, timestamp_type warn_type,
 
652
                  char *warn_name, bool *error_arg)
 
653
{
 
654
  ulonglong value= 0;
 
655
  int error;
 
656
  MYSQL_TIME l_time;
 
657
  enum_mysql_timestamp_type ret;
 
658
 
 
659
  ret= str_to_datetime(str->ptr(), str->length(), &l_time,
 
660
                       (TIME_FUZZY_DATE | MODE_INVALID_DATES |
 
661
                        (thd->variables.sql_mode &
 
662
                         (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE))),
 
663
                       &error);
 
664
 
 
665
  if (ret == MYSQL_TIMESTAMP_DATETIME || ret == MYSQL_TIMESTAMP_DATE)
 
666
  {
 
667
    /*
 
668
      Do not return yet, we may still want to throw a "trailing garbage"
 
669
      warning.
 
670
    */
 
671
    *error_arg= FALSE;
 
672
    value= TIME_to_ulonglong_datetime(&l_time);
 
673
  }
 
674
  else
 
675
  {
 
676
    *error_arg= TRUE;
 
677
    error= 1;                                   /* force warning */
 
678
  }
 
679
 
 
680
  if (error > 0)
 
681
    make_truncated_value_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
682
                                 str->ptr(), str->length(),
 
683
                                 warn_type, warn_name);
 
684
 
 
685
  return value;
 
686
}
 
687
 
 
688
 
 
689
/*
 
690
  Check whether compare_datetime() can be used to compare items.
 
691
 
 
692
  SYNOPSIS
 
693
    Arg_comparator::can_compare_as_dates()
 
694
    a, b          [in]  items to be compared
 
695
    const_value   [out] converted value of the string constant, if any
 
696
 
 
697
  DESCRIPTION
 
698
    Check several cases when the DATE/DATETIME comparator should be used.
 
699
    The following cases are checked:
 
700
      1. Both a and b is a DATE/DATETIME field/function returning string or
 
701
         int result.
 
702
      2. Only a or b is a DATE/DATETIME field/function returning string or
 
703
         int result and the other item (b or a) is an item with string result.
 
704
         If the second item is a constant one then it's checked to be
 
705
         convertible to the DATE/DATETIME type. If the constant can't be
 
706
         converted to a DATE/DATETIME then the compare_datetime() comparator
 
707
         isn't used and the warning about wrong DATE/DATETIME value is issued.
 
708
      In all other cases (date-[int|real|decimal]/[int|real|decimal]-date)
 
709
      the comparison is handled by other comparators.
 
710
    If the datetime comparator can be used and one the operands of the
 
711
    comparison is a string constant that was successfully converted to a
 
712
    DATE/DATETIME type then the result of the conversion is returned in the
 
713
    const_value if it is provided.  If there is no constant or
 
714
    compare_datetime() isn't applicable then the *const_value remains
 
715
    unchanged.
 
716
 
 
717
  RETURN
 
718
    the found type of date comparison
 
719
*/
 
720
 
 
721
enum Arg_comparator::enum_date_cmp_type
 
722
Arg_comparator::can_compare_as_dates(Item *a, Item *b, ulonglong *const_value)
 
723
{
 
724
  enum enum_date_cmp_type cmp_type= CMP_DATE_DFLT;
 
725
  Item *str_arg= 0, *date_arg= 0;
 
726
 
 
727
  if (a->type() == Item::ROW_ITEM || b->type() == Item::ROW_ITEM)
 
728
    return CMP_DATE_DFLT;
 
729
 
 
730
  if (a->is_datetime())
 
731
  {
 
732
    if (b->is_datetime())
 
733
      cmp_type= CMP_DATE_WITH_DATE;
 
734
    else if (b->result_type() == STRING_RESULT)
 
735
    {
 
736
      cmp_type= CMP_DATE_WITH_STR;
 
737
      date_arg= a;
 
738
      str_arg= b;
 
739
    }
 
740
  }
 
741
  else if (b->is_datetime() && a->result_type() == STRING_RESULT)
 
742
  {
 
743
    cmp_type= CMP_STR_WITH_DATE;
 
744
    date_arg= b;
 
745
    str_arg= a;
 
746
  }
 
747
 
 
748
  if (cmp_type != CMP_DATE_DFLT)
 
749
  {
 
750
    /*
 
751
      Do not cache GET_USER_VAR() function as its const_item() may return TRUE
 
752
      for the current thread but it still may change during the execution.
 
753
    */
 
754
    if (cmp_type != CMP_DATE_WITH_DATE && str_arg->const_item() &&
 
755
        (str_arg->type() != Item::FUNC_ITEM ||
 
756
        ((Item_func*)str_arg)->functype() != Item_func::GUSERVAR_FUNC))
 
757
    {
 
758
      THD *thd= current_thd;
 
759
      ulonglong value;
 
760
      bool error;
 
761
      String tmp, *str_val= 0;
 
762
      timestamp_type t_type= (date_arg->field_type() == MYSQL_TYPE_DATE ?
 
763
                              MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME);
 
764
 
 
765
      str_val= str_arg->val_str(&tmp);
 
766
      if (str_arg->null_value)
 
767
        return CMP_DATE_DFLT;
 
768
      value= get_date_from_str(thd, str_val, t_type, date_arg->name, &error);
 
769
      if (error)
 
770
        return CMP_DATE_DFLT;
 
771
      if (const_value)
 
772
        *const_value= value;
 
773
    }
 
774
  }
 
775
  return cmp_type;
 
776
}
 
777
 
 
778
 
 
779
/*
 
780
  Retrieves correct TIME value from the given item.
 
781
 
 
782
  SYNOPSIS
 
783
    get_time_value()
 
784
    thd                 thread handle
 
785
    item_arg   [in/out] item to retrieve TIME value from
 
786
    cache_arg  [in/out] pointer to place to store the cache item to
 
787
    warn_item  [in]     unused
 
788
    is_null    [out]    TRUE <=> the item_arg is null
 
789
 
 
790
  DESCRIPTION
 
791
    Retrieves the correct TIME value from given item for comparison by the
 
792
    compare_datetime() function.
 
793
    If item's result can be compared as longlong then its int value is used
 
794
    and a value returned by get_time function is used otherwise.
 
795
    If an item is a constant one then its value is cached and it isn't
 
796
    get parsed again. An Item_cache_int object is used for for cached values.
 
797
    It seamlessly substitutes the original item.  The cache item is marked as
 
798
    non-constant to prevent re-caching it again.
 
799
 
 
800
  RETURN
 
801
    obtained value
 
802
*/
 
803
 
 
804
ulonglong
 
805
get_time_value(THD *thd, Item ***item_arg, Item **cache_arg,
 
806
               Item *warn_item, bool *is_null)
 
807
{
 
808
  ulonglong value;
 
809
  Item *item= **item_arg;
 
810
  MYSQL_TIME ltime;
 
811
 
 
812
  if (item->result_as_longlong())
 
813
  {
 
814
    value= item->val_int();
 
815
    *is_null= item->null_value;
 
816
  }
 
817
  else
 
818
  {
 
819
    *is_null= item->get_time(&ltime);
 
820
    value= !*is_null ? TIME_to_ulonglong_datetime(&ltime) : 0;
 
821
  }
 
822
  /*
 
823
    Do not cache GET_USER_VAR() function as its const_item() may return TRUE
 
824
    for the current thread but it still may change during the execution.
 
825
  */
 
826
  if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM ||
 
827
      ((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
 
828
  {
 
829
    Item_cache_int *cache= new Item_cache_int();
 
830
    /* Mark the cache as non-const to prevent re-caching. */
 
831
    cache->set_used_tables(1);
 
832
    cache->store(item, value);
 
833
    *cache_arg= cache;
 
834
    *item_arg= cache_arg;
 
835
  }
 
836
  return value;
 
837
}
 
838
 
 
839
 
 
840
int Arg_comparator::set_cmp_func(Item_bool_func2 *owner_arg,
 
841
                                        Item **a1, Item **a2,
 
842
                                        Item_result type)
 
843
{
 
844
  enum enum_date_cmp_type cmp_type;
 
845
  ulonglong const_value= (ulonglong)-1;
 
846
  a= a1;
 
847
  b= a2;
 
848
 
 
849
  if ((cmp_type= can_compare_as_dates(*a, *b, &const_value)))
 
850
  {
 
851
    thd= current_thd;
 
852
    owner= owner_arg;
 
853
    a_type= (*a)->field_type();
 
854
    b_type= (*b)->field_type();
 
855
    a_cache= 0;
 
856
    b_cache= 0;
 
857
 
 
858
    if (const_value != (ulonglong)-1)
 
859
    {
 
860
      Item_cache_int *cache= new Item_cache_int();
 
861
      /* Mark the cache as non-const to prevent re-caching. */
 
862
      cache->set_used_tables(1);
 
863
      if (!(*a)->is_datetime())
 
864
      {
 
865
        cache->store((*a), const_value);
 
866
        a_cache= cache;
 
867
        a= (Item **)&a_cache;
 
868
      }
 
869
      else
 
870
      {
 
871
        cache->store((*b), const_value);
 
872
        b_cache= cache;
 
873
        b= (Item **)&b_cache;
 
874
      }
 
875
    }
 
876
    is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC);
 
877
    func= &Arg_comparator::compare_datetime;
 
878
    get_value_func= &get_datetime_value;
 
879
    return 0;
 
880
  }
 
881
  else if (type == STRING_RESULT && (*a)->field_type() == MYSQL_TYPE_TIME &&
 
882
           (*b)->field_type() == MYSQL_TYPE_TIME)
 
883
  {
 
884
    /* Compare TIME values as integers. */
 
885
    thd= current_thd;
 
886
    owner= owner_arg;
 
887
    a_cache= 0;
 
888
    b_cache= 0;
 
889
    is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC);
 
890
    func= &Arg_comparator::compare_datetime;
 
891
    get_value_func= &get_time_value;
 
892
    return 0;
 
893
  }
 
894
 
 
895
  return set_compare_func(owner_arg, type);
 
896
}
 
897
 
 
898
 
 
899
void Arg_comparator::set_datetime_cmp_func(Item **a1, Item **b1)
 
900
{
 
901
  thd= current_thd;
 
902
  /* A caller will handle null values by itself. */
 
903
  owner= NULL;
 
904
  a= a1;
 
905
  b= b1;
 
906
  a_type= (*a)->field_type();
 
907
  b_type= (*b)->field_type();
 
908
  a_cache= 0;
 
909
  b_cache= 0;
 
910
  is_nulls_eq= FALSE;
 
911
  func= &Arg_comparator::compare_datetime;
 
912
  get_value_func= &get_datetime_value;
 
913
}
 
914
 
 
915
 
 
916
/*
 
917
  Retrieves correct DATETIME value from given item.
 
918
 
 
919
  SYNOPSIS
 
920
    get_datetime_value()
 
921
    thd                 thread handle
 
922
    item_arg   [in/out] item to retrieve DATETIME value from
 
923
    cache_arg  [in/out] pointer to place to store the caching item to
 
924
    warn_item  [in]     item for issuing the conversion warning
 
925
    is_null    [out]    TRUE <=> the item_arg is null
 
926
 
 
927
  DESCRIPTION
 
928
    Retrieves the correct DATETIME value from given item for comparison by the
 
929
    compare_datetime() function.
 
930
    If item's result can be compared as longlong then its int value is used
 
931
    and its string value is used otherwise. Strings are always parsed and
 
932
    converted to int values by the get_date_from_str() function.
 
933
    This allows us to compare correctly string dates with missed insignificant
 
934
    zeros. If an item is a constant one then its value is cached and it isn't
 
935
    get parsed again. An Item_cache_int object is used for caching values. It
 
936
    seamlessly substitutes the original item.  The cache item is marked as
 
937
    non-constant to prevent re-caching it again.  In order to compare
 
938
    correctly DATE and DATETIME items the result of the former are treated as
 
939
    a DATETIME with zero time (00:00:00).
 
940
 
 
941
  RETURN
 
942
    obtained value
 
943
*/
 
944
 
 
945
ulonglong
 
946
get_datetime_value(THD *thd, Item ***item_arg, Item **cache_arg,
 
947
                   Item *warn_item, bool *is_null)
 
948
{
 
949
  ulonglong value= 0;
 
950
  String buf, *str= 0;
 
951
  Item *item= **item_arg;
 
952
 
 
953
  if (item->result_as_longlong())
 
954
  {
 
955
    value= item->val_int();
 
956
    *is_null= item->null_value;
 
957
    enum_field_types f_type= item->field_type();
 
958
    /*
 
959
      Item_date_add_interval may return MYSQL_TYPE_STRING as the result
 
960
      field type. To detect that the DATE value has been returned we
 
961
      compare it with 100000000L - any DATE value should be less than it.
 
962
      Don't shift cached DATETIME values up for the second time.
 
963
    */
 
964
    if (f_type == MYSQL_TYPE_DATE ||
 
965
        (f_type != MYSQL_TYPE_DATETIME && value < 100000000L))
 
966
      value*= 1000000L;
 
967
  }
 
968
  else
 
969
  {
 
970
    str= item->val_str(&buf);
 
971
    *is_null= item->null_value;
 
972
  }
 
973
  if (*is_null)
 
974
    return ~(ulonglong) 0;
 
975
  /*
 
976
    Convert strings to the integer DATE/DATETIME representation.
 
977
    Even if both dates provided in strings we can't compare them directly as
 
978
    strings as there is no warranty that they are correct and do not miss
 
979
    some insignificant zeros.
 
980
  */
 
981
  if (str)
 
982
  {
 
983
    bool error;
 
984
    enum_field_types f_type= warn_item->field_type();
 
985
    timestamp_type t_type= f_type ==
 
986
      MYSQL_TYPE_DATE ? MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME;
 
987
    value= get_date_from_str(thd, str, t_type, warn_item->name, &error);
 
988
    /*
 
989
      If str did not contain a valid date according to the current
 
990
      SQL_MODE, get_date_from_str() has already thrown a warning,
 
991
      and we don't want to throw NULL on invalid date (see 5.2.6
 
992
      "SQL modes" in the manual), so we're done here.
 
993
    */
 
994
  }
 
995
  /*
 
996
    Do not cache GET_USER_VAR() function as its const_item() may return TRUE
 
997
    for the current thread but it still may change during the execution.
 
998
  */
 
999
  if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM ||
 
1000
      ((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
 
1001
  {
 
1002
    Item_cache_int *cache= new Item_cache_int(MYSQL_TYPE_DATETIME);
 
1003
    /* Mark the cache as non-const to prevent re-caching. */
 
1004
    cache->set_used_tables(1);
 
1005
    cache->store(item, value);
 
1006
    *cache_arg= cache;
 
1007
    *item_arg= cache_arg;
 
1008
  }
 
1009
  return value;
 
1010
}
 
1011
 
 
1012
/*
 
1013
  Compare items values as dates.
 
1014
 
 
1015
  SYNOPSIS
 
1016
    Arg_comparator::compare_datetime()
 
1017
 
 
1018
  DESCRIPTION
 
1019
    Compare items values as DATE/DATETIME for both EQUAL_FUNC and from other
 
1020
    comparison functions. The correct DATETIME values are obtained
 
1021
    with help of the get_datetime_value() function.
 
1022
 
 
1023
  RETURN
 
1024
    If is_nulls_eq is TRUE:
 
1025
       1    if items are equal or both are null
 
1026
       0    otherwise
 
1027
    If is_nulls_eq is FALSE:
 
1028
      -1   a < b or one of items is null
 
1029
       0   a == b
 
1030
       1   a > b
 
1031
*/
 
1032
 
 
1033
int Arg_comparator::compare_datetime()
 
1034
{
 
1035
  bool is_null= FALSE;
 
1036
  ulonglong a_value, b_value;
 
1037
 
 
1038
  /* Get DATE/DATETIME/TIME value of the 'a' item. */
 
1039
  a_value= (*get_value_func)(thd, &a, &a_cache, *b, &is_null);
 
1040
  if (!is_nulls_eq && is_null)
 
1041
  {
 
1042
    if (owner)
 
1043
      owner->null_value= 1;
 
1044
    return -1;
 
1045
  }
 
1046
 
 
1047
  /* Get DATE/DATETIME/TIME value of the 'b' item. */
 
1048
  b_value= (*get_value_func)(thd, &b, &b_cache, *a, &is_null);
 
1049
  if (is_null)
 
1050
  {
 
1051
    if (owner)
 
1052
      owner->null_value= is_nulls_eq ? 0 : 1;
 
1053
    return is_nulls_eq ? 1 : -1;
 
1054
  }
 
1055
 
 
1056
  if (owner)
 
1057
    owner->null_value= 0;
 
1058
 
 
1059
  /* Compare values. */
 
1060
  if (is_nulls_eq)
 
1061
    return (a_value == b_value);
 
1062
  return a_value < b_value ? -1 : (a_value > b_value ? 1 : 0);
 
1063
}
 
1064
 
 
1065
 
 
1066
int Arg_comparator::compare_string()
 
1067
{
 
1068
  String *res1,*res2;
 
1069
  if ((res1= (*a)->val_str(&owner->tmp_value1)))
 
1070
  {
 
1071
    if ((res2= (*b)->val_str(&owner->tmp_value2)))
 
1072
    {
 
1073
      owner->null_value= 0;
 
1074
      return sortcmp(res1,res2,cmp_collation.collation);
 
1075
    }
 
1076
  }
 
1077
  owner->null_value= 1;
 
1078
  return -1;
 
1079
}
 
1080
 
 
1081
 
 
1082
/**
 
1083
  Compare strings byte by byte. End spaces are also compared.
 
1084
 
 
1085
  @retval
 
1086
    <0  *a < *b
 
1087
  @retval
 
1088
     0  *b == *b
 
1089
  @retval
 
1090
    >0  *a > *b
 
1091
*/
 
1092
 
 
1093
int Arg_comparator::compare_binary_string()
 
1094
{
 
1095
  String *res1,*res2;
 
1096
  if ((res1= (*a)->val_str(&owner->tmp_value1)))
 
1097
  {
 
1098
    if ((res2= (*b)->val_str(&owner->tmp_value2)))
 
1099
    {
 
1100
      owner->null_value= 0;
 
1101
      uint res1_length= res1->length();
 
1102
      uint res2_length= res2->length();
 
1103
      int cmp= memcmp(res1->ptr(), res2->ptr(), min(res1_length,res2_length));
 
1104
      return cmp ? cmp : (int) (res1_length - res2_length);
 
1105
    }
 
1106
  }
 
1107
  owner->null_value= 1;
 
1108
  return -1;
 
1109
}
 
1110
 
 
1111
 
 
1112
/**
 
1113
  Compare strings, but take into account that NULL == NULL.
 
1114
*/
 
1115
 
 
1116
 
 
1117
int Arg_comparator::compare_e_string()
 
1118
{
 
1119
  String *res1,*res2;
 
1120
  res1= (*a)->val_str(&owner->tmp_value1);
 
1121
  res2= (*b)->val_str(&owner->tmp_value2);
 
1122
  if (!res1 || !res2)
 
1123
    return test(res1 == res2);
 
1124
  return test(sortcmp(res1, res2, cmp_collation.collation) == 0);
 
1125
}
 
1126
 
 
1127
 
 
1128
int Arg_comparator::compare_e_binary_string()
 
1129
{
 
1130
  String *res1,*res2;
 
1131
  res1= (*a)->val_str(&owner->tmp_value1);
 
1132
  res2= (*b)->val_str(&owner->tmp_value2);
 
1133
  if (!res1 || !res2)
 
1134
    return test(res1 == res2);
 
1135
  return test(stringcmp(res1, res2) == 0);
 
1136
}
 
1137
 
 
1138
 
 
1139
int Arg_comparator::compare_real()
 
1140
{
 
1141
  /*
 
1142
    Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
 
1143
    gcc to flush double values out of 80-bit Intel FPU registers before
 
1144
    performing the comparison.
 
1145
  */
 
1146
  volatile double val1, val2;
 
1147
  val1= (*a)->val_real();
 
1148
  if (!(*a)->null_value)
 
1149
  {
 
1150
    val2= (*b)->val_real();
 
1151
    if (!(*b)->null_value)
 
1152
    {
 
1153
      owner->null_value= 0;
 
1154
      if (val1 < val2)  return -1;
 
1155
      if (val1 == val2) return 0;
 
1156
      return 1;
 
1157
    }
 
1158
  }
 
1159
  owner->null_value= 1;
 
1160
  return -1;
 
1161
}
 
1162
 
 
1163
int Arg_comparator::compare_decimal()
 
1164
{
 
1165
  my_decimal value1;
 
1166
  my_decimal *val1= (*a)->val_decimal(&value1);
 
1167
  if (!(*a)->null_value)
 
1168
  {
 
1169
    my_decimal value2;
 
1170
    my_decimal *val2= (*b)->val_decimal(&value2);
 
1171
    if (!(*b)->null_value)
 
1172
    {
 
1173
      owner->null_value= 0;
 
1174
      return my_decimal_cmp(val1, val2);
 
1175
    }
 
1176
  }
 
1177
  owner->null_value= 1;
 
1178
  return -1;
 
1179
}
 
1180
 
 
1181
int Arg_comparator::compare_e_real()
 
1182
{
 
1183
  double val1= (*a)->val_real();
 
1184
  double val2= (*b)->val_real();
 
1185
  if ((*a)->null_value || (*b)->null_value)
 
1186
    return test((*a)->null_value && (*b)->null_value);
 
1187
  return test(val1 == val2);
 
1188
}
 
1189
 
 
1190
int Arg_comparator::compare_e_decimal()
 
1191
{
 
1192
  my_decimal value1, value2;
 
1193
  my_decimal *val1= (*a)->val_decimal(&value1);
 
1194
  my_decimal *val2= (*b)->val_decimal(&value2);
 
1195
  if ((*a)->null_value || (*b)->null_value)
 
1196
    return test((*a)->null_value && (*b)->null_value);
 
1197
  return test(my_decimal_cmp(val1, val2) == 0);
 
1198
}
 
1199
 
 
1200
 
 
1201
int Arg_comparator::compare_real_fixed()
 
1202
{
 
1203
  /*
 
1204
    Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
 
1205
    gcc to flush double values out of 80-bit Intel FPU registers before
 
1206
    performing the comparison.
 
1207
  */
 
1208
  volatile double val1, val2;
 
1209
  val1= (*a)->val_real();
 
1210
  if (!(*a)->null_value)
 
1211
  {
 
1212
    val2= (*b)->val_real();
 
1213
    if (!(*b)->null_value)
 
1214
    {
 
1215
      owner->null_value= 0;
 
1216
      if (val1 == val2 || fabs(val1 - val2) < precision)
 
1217
        return 0;
 
1218
      if (val1 < val2)
 
1219
        return -1;
 
1220
      return 1;
 
1221
    }
 
1222
  }
 
1223
  owner->null_value= 1;
 
1224
  return -1;
 
1225
}
 
1226
 
 
1227
 
 
1228
int Arg_comparator::compare_e_real_fixed()
 
1229
{
 
1230
  double val1= (*a)->val_real();
 
1231
  double val2= (*b)->val_real();
 
1232
  if ((*a)->null_value || (*b)->null_value)
 
1233
    return test((*a)->null_value && (*b)->null_value);
 
1234
  return test(val1 == val2 || fabs(val1 - val2) < precision);
 
1235
}
 
1236
 
 
1237
 
 
1238
int Arg_comparator::compare_int_signed()
 
1239
{
 
1240
  longlong val1= (*a)->val_int();
 
1241
  if (!(*a)->null_value)
 
1242
  {
 
1243
    longlong val2= (*b)->val_int();
 
1244
    if (!(*b)->null_value)
 
1245
    {
 
1246
      owner->null_value= 0;
 
1247
      if (val1 < val2)  return -1;
 
1248
      if (val1 == val2)   return 0;
 
1249
      return 1;
 
1250
    }
 
1251
  }
 
1252
  owner->null_value= 1;
 
1253
  return -1;
 
1254
}
 
1255
 
 
1256
 
 
1257
/**
 
1258
  Compare values as BIGINT UNSIGNED.
 
1259
*/
 
1260
 
 
1261
int Arg_comparator::compare_int_unsigned()
 
1262
{
 
1263
  ulonglong val1= (*a)->val_int();
 
1264
  if (!(*a)->null_value)
 
1265
  {
 
1266
    ulonglong val2= (*b)->val_int();
 
1267
    if (!(*b)->null_value)
 
1268
    {
 
1269
      owner->null_value= 0;
 
1270
      if (val1 < val2)  return -1;
 
1271
      if (val1 == val2)   return 0;
 
1272
      return 1;
 
1273
    }
 
1274
  }
 
1275
  owner->null_value= 1;
 
1276
  return -1;
 
1277
}
 
1278
 
 
1279
 
 
1280
/**
 
1281
  Compare signed (*a) with unsigned (*B)
 
1282
*/
 
1283
 
 
1284
int Arg_comparator::compare_int_signed_unsigned()
 
1285
{
 
1286
  longlong sval1= (*a)->val_int();
 
1287
  if (!(*a)->null_value)
 
1288
  {
 
1289
    ulonglong uval2= (ulonglong)(*b)->val_int();
 
1290
    if (!(*b)->null_value)
 
1291
    {
 
1292
      owner->null_value= 0;
 
1293
      if (sval1 < 0 || (ulonglong)sval1 < uval2)
 
1294
        return -1;
 
1295
      if ((ulonglong)sval1 == uval2)
 
1296
        return 0;
 
1297
      return 1;
 
1298
    }
 
1299
  }
 
1300
  owner->null_value= 1;
 
1301
  return -1;
 
1302
}
 
1303
 
 
1304
 
 
1305
/**
 
1306
  Compare unsigned (*a) with signed (*B)
 
1307
*/
 
1308
 
 
1309
int Arg_comparator::compare_int_unsigned_signed()
 
1310
{
 
1311
  ulonglong uval1= (ulonglong)(*a)->val_int();
 
1312
  if (!(*a)->null_value)
 
1313
  {
 
1314
    longlong sval2= (*b)->val_int();
 
1315
    if (!(*b)->null_value)
 
1316
    {
 
1317
      owner->null_value= 0;
 
1318
      if (sval2 < 0)
 
1319
        return 1;
 
1320
      if (uval1 < (ulonglong)sval2)
 
1321
        return -1;
 
1322
      if (uval1 == (ulonglong)sval2)
 
1323
        return 0;
 
1324
      return 1;
 
1325
    }
 
1326
  }
 
1327
  owner->null_value= 1;
 
1328
  return -1;
 
1329
}
 
1330
 
 
1331
 
 
1332
int Arg_comparator::compare_e_int()
 
1333
{
 
1334
  longlong val1= (*a)->val_int();
 
1335
  longlong val2= (*b)->val_int();
 
1336
  if ((*a)->null_value || (*b)->null_value)
 
1337
    return test((*a)->null_value && (*b)->null_value);
 
1338
  return test(val1 == val2);
 
1339
}
 
1340
 
 
1341
/**
 
1342
  Compare unsigned *a with signed *b or signed *a with unsigned *b.
 
1343
*/
 
1344
int Arg_comparator::compare_e_int_diff_signedness()
 
1345
{
 
1346
  longlong val1= (*a)->val_int();
 
1347
  longlong val2= (*b)->val_int();
 
1348
  if ((*a)->null_value || (*b)->null_value)
 
1349
    return test((*a)->null_value && (*b)->null_value);
 
1350
  return (val1 >= 0) && test(val1 == val2);
 
1351
}
 
1352
 
 
1353
int Arg_comparator::compare_row()
 
1354
{
 
1355
  int res= 0;
 
1356
  bool was_null= 0;
 
1357
  (*a)->bring_value();
 
1358
  (*b)->bring_value();
 
1359
  uint n= (*a)->cols();
 
1360
  for (uint i= 0; i<n; i++)
 
1361
  {
 
1362
    res= comparators[i].compare();
 
1363
    if (owner->null_value)
 
1364
    {
 
1365
      // NULL was compared
 
1366
      switch (owner->functype()) {
 
1367
      case Item_func::NE_FUNC:
 
1368
        break; // NE never aborts on NULL even if abort_on_null is set
 
1369
      case Item_func::LT_FUNC:
 
1370
      case Item_func::LE_FUNC:
 
1371
      case Item_func::GT_FUNC:
 
1372
      case Item_func::GE_FUNC:
 
1373
        return -1; // <, <=, > and >= always fail on NULL
 
1374
      default: // EQ_FUNC
 
1375
        if (owner->abort_on_null)
 
1376
          return -1; // We do not need correct NULL returning
 
1377
      }
 
1378
      was_null= 1;
 
1379
      owner->null_value= 0;
 
1380
      res= 0;  // continue comparison (maybe we will meet explicit difference)
 
1381
    }
 
1382
    else if (res)
 
1383
      return res;
 
1384
  }
 
1385
  if (was_null)
 
1386
  {
 
1387
    /*
 
1388
      There was NULL(s) in comparison in some parts, but there was no
 
1389
      explicit difference in other parts, so we have to return NULL.
 
1390
    */
 
1391
    owner->null_value= 1;
 
1392
    return -1;
 
1393
  }
 
1394
  return 0;
 
1395
}
 
1396
 
 
1397
 
 
1398
int Arg_comparator::compare_e_row()
 
1399
{
 
1400
  (*a)->bring_value();
 
1401
  (*b)->bring_value();
 
1402
  uint n= (*a)->cols();
 
1403
  for (uint i= 0; i<n; i++)
 
1404
  {
 
1405
    if (!comparators[i].compare())
 
1406
      return 0;
 
1407
  }
 
1408
  return 1;
 
1409
}
 
1410
 
 
1411
 
 
1412
void Item_func_truth::fix_length_and_dec()
 
1413
{
 
1414
  maybe_null= 0;
 
1415
  null_value= 0;
 
1416
  decimals= 0;
 
1417
  max_length= 1;
 
1418
}
 
1419
 
 
1420
 
 
1421
void Item_func_truth::print(String *str, enum_query_type query_type)
 
1422
{
 
1423
  str->append('(');
 
1424
  args[0]->print(str, query_type);
 
1425
  str->append(STRING_WITH_LEN(" is "));
 
1426
  if (! affirmative)
 
1427
    str->append(STRING_WITH_LEN("not "));
 
1428
  if (value)
 
1429
    str->append(STRING_WITH_LEN("true"));
 
1430
  else
 
1431
    str->append(STRING_WITH_LEN("false"));
 
1432
  str->append(')');
 
1433
}
 
1434
 
 
1435
 
 
1436
bool Item_func_truth::val_bool()
 
1437
{
 
1438
  bool val= args[0]->val_bool();
 
1439
  if (args[0]->null_value)
 
1440
  {
 
1441
    /*
 
1442
      NULL val IS {TRUE, FALSE} --> FALSE
 
1443
      NULL val IS NOT {TRUE, FALSE} --> TRUE
 
1444
    */
 
1445
    return (! affirmative);
 
1446
  }
 
1447
 
 
1448
  if (affirmative)
 
1449
  {
 
1450
    /* {TRUE, FALSE} val IS {TRUE, FALSE} value */
 
1451
    return (val == value);
 
1452
  }
 
1453
 
 
1454
  /* {TRUE, FALSE} val IS NOT {TRUE, FALSE} value */
 
1455
  return (val != value);
 
1456
}
 
1457
 
 
1458
 
 
1459
longlong Item_func_truth::val_int()
 
1460
{
 
1461
  return (val_bool() ? 1 : 0);
 
1462
}
 
1463
 
 
1464
 
 
1465
bool Item_in_optimizer::fix_left(THD *thd, Item **ref)
 
1466
{
 
1467
  if ((!args[0]->fixed && args[0]->fix_fields(thd, args)) ||
 
1468
      (!cache && !(cache= Item_cache::get_cache(args[0]))))
 
1469
    return 1;
 
1470
 
 
1471
  cache->setup(args[0]);
 
1472
  if (cache->cols() == 1)
 
1473
  {
 
1474
    if ((used_tables_cache= args[0]->used_tables()))
 
1475
      cache->set_used_tables(OUTER_REF_TABLE_BIT);
 
1476
    else
 
1477
      cache->set_used_tables(0);
 
1478
  }
 
1479
  else
 
1480
  {
 
1481
    uint n= cache->cols();
 
1482
    for (uint i= 0; i < n; i++)
 
1483
    {
 
1484
      if (args[0]->element_index(i)->used_tables())
 
1485
        ((Item_cache *)cache->element_index(i))->set_used_tables(OUTER_REF_TABLE_BIT);
 
1486
      else
 
1487
        ((Item_cache *)cache->element_index(i))->set_used_tables(0);
 
1488
    }
 
1489
    used_tables_cache= args[0]->used_tables();
 
1490
  }
 
1491
  not_null_tables_cache= args[0]->not_null_tables();
 
1492
  with_sum_func= args[0]->with_sum_func;
 
1493
  if ((const_item_cache= args[0]->const_item()))
 
1494
    cache->store(args[0]);
 
1495
  return 0;
 
1496
}
 
1497
 
 
1498
 
 
1499
bool Item_in_optimizer::fix_fields(THD *thd, Item **ref)
 
1500
{
 
1501
  DBUG_ASSERT(fixed == 0);
 
1502
  if (fix_left(thd, ref))
 
1503
    return TRUE;
 
1504
  if (args[0]->maybe_null)
 
1505
    maybe_null=1;
 
1506
 
 
1507
  if (!args[1]->fixed && args[1]->fix_fields(thd, args+1))
 
1508
    return TRUE;
 
1509
  Item_in_subselect * sub= (Item_in_subselect *)args[1];
 
1510
  if (args[0]->cols() != sub->engine->cols())
 
1511
  {
 
1512
    my_error(ER_OPERAND_COLUMNS, MYF(0), args[0]->cols());
 
1513
    return TRUE;
 
1514
  }
 
1515
  if (args[1]->maybe_null)
 
1516
    maybe_null=1;
 
1517
  with_sum_func= with_sum_func || args[1]->with_sum_func;
 
1518
  used_tables_cache|= args[1]->used_tables();
 
1519
  not_null_tables_cache|= args[1]->not_null_tables();
 
1520
  const_item_cache&= args[1]->const_item();
 
1521
  fixed= 1;
 
1522
  return FALSE;
 
1523
}
 
1524
 
 
1525
 
 
1526
longlong Item_in_optimizer::val_int()
 
1527
{
 
1528
  bool tmp;
 
1529
  DBUG_ASSERT(fixed == 1);
 
1530
  cache->store(args[0]);
 
1531
  
 
1532
  if (cache->null_value)
 
1533
  {
 
1534
    if (((Item_in_subselect*)args[1])->is_top_level_item())
 
1535
    {
 
1536
      /*
 
1537
        We're evaluating "NULL IN (SELECT ...)". The result can be NULL or
 
1538
        FALSE, and we can return one instead of another. Just return NULL.
 
1539
      */
 
1540
      null_value= 1;
 
1541
    }
 
1542
    else
 
1543
    {
 
1544
      if (!((Item_in_subselect*)args[1])->is_correlated &&
 
1545
          result_for_null_param != UNKNOWN)
 
1546
      {
 
1547
        /* Use cached value from previous execution */
 
1548
        null_value= result_for_null_param;
 
1549
      }
 
1550
      else
 
1551
      {
 
1552
        /*
 
1553
          We're evaluating "NULL IN (SELECT ...)". The result is:
 
1554
             FALSE if SELECT produces an empty set, or
 
1555
             NULL  otherwise.
 
1556
          We disable the predicates we've pushed down into subselect, run the
 
1557
          subselect and see if it has produced any rows.
 
1558
        */
 
1559
        Item_in_subselect *item_subs=(Item_in_subselect*)args[1]; 
 
1560
        if (cache->cols() == 1)
 
1561
        {
 
1562
          item_subs->set_cond_guard_var(0, FALSE);
 
1563
          (void) args[1]->val_bool_result();
 
1564
          result_for_null_param= null_value= !item_subs->engine->no_rows();
 
1565
          item_subs->set_cond_guard_var(0, TRUE);
 
1566
        }
 
1567
        else
 
1568
        {
 
1569
          uint i;
 
1570
          uint ncols= cache->cols();
 
1571
          /*
 
1572
            Turn off the predicates that are based on column compares for
 
1573
            which the left part is currently NULL
 
1574
          */
 
1575
          for (i= 0; i < ncols; i++)
 
1576
          {
 
1577
            if (cache->element_index(i)->null_value)
 
1578
              item_subs->set_cond_guard_var(i, FALSE);
 
1579
          }
 
1580
          
 
1581
          (void) args[1]->val_bool_result();
 
1582
          result_for_null_param= null_value= !item_subs->engine->no_rows();
 
1583
          
 
1584
          /* Turn all predicates back on */
 
1585
          for (i= 0; i < ncols; i++)
 
1586
            item_subs->set_cond_guard_var(i, TRUE);
 
1587
        }
 
1588
      }
 
1589
    }
 
1590
    return 0;
 
1591
  }
 
1592
  tmp= args[1]->val_bool_result();
 
1593
  null_value= args[1]->null_value;
 
1594
  return tmp;
 
1595
}
 
1596
 
 
1597
 
 
1598
void Item_in_optimizer::keep_top_level_cache()
 
1599
{
 
1600
  cache->keep_array();
 
1601
  save_cache= 1;
 
1602
}
 
1603
 
 
1604
 
 
1605
void Item_in_optimizer::cleanup()
 
1606
{
 
1607
  DBUG_ENTER("Item_in_optimizer::cleanup");
 
1608
  Item_bool_func::cleanup();
 
1609
  if (!save_cache)
 
1610
    cache= 0;
 
1611
  DBUG_VOID_RETURN;
 
1612
}
 
1613
 
 
1614
 
 
1615
bool Item_in_optimizer::is_null()
 
1616
{
 
1617
  cache->store(args[0]);
 
1618
  return (null_value= (cache->null_value || args[1]->is_null()));
 
1619
}
 
1620
 
 
1621
 
 
1622
/**
 
1623
  Transform an Item_in_optimizer and its arguments with a callback function.
 
1624
 
 
1625
  @param transformer the transformer callback function to be applied to the
 
1626
         nodes of the tree of the object
 
1627
  @param parameter to be passed to the transformer
 
1628
 
 
1629
  @detail
 
1630
    Recursively transform the left and the right operand of this Item. The
 
1631
    Right operand is an Item_in_subselect or its subclass. To avoid the
 
1632
    creation of new Items, we use the fact the the left operand of the
 
1633
    Item_in_subselect is the same as the one of 'this', so instead of
 
1634
    transforming its operand, we just assign the left operand of the
 
1635
    Item_in_subselect to be equal to the left operand of 'this'.
 
1636
    The transformation is not applied further to the subquery operand
 
1637
    if the IN predicate.
 
1638
 
 
1639
  @returns
 
1640
    @retval pointer to the transformed item
 
1641
    @retval NULL if an error occurred
 
1642
*/
 
1643
 
 
1644
Item *Item_in_optimizer::transform(Item_transformer transformer, uchar *argument)
 
1645
{
 
1646
  Item *new_item;
 
1647
 
 
1648
  DBUG_ASSERT(arg_count == 2);
 
1649
 
 
1650
  /* Transform the left IN operand. */
 
1651
  new_item= (*args)->transform(transformer, argument);
 
1652
  if (!new_item)
 
1653
    return 0;
 
1654
  /*
 
1655
    THD::change_item_tree() should be called only if the tree was
 
1656
    really transformed, i.e. when a new item has been created.
 
1657
    Otherwise we'll be allocating a lot of unnecessary memory for
 
1658
    change records at each execution.
 
1659
  */
 
1660
  if ((*args) != new_item)
 
1661
    current_thd->change_item_tree(args, new_item);
 
1662
 
 
1663
  /*
 
1664
    Transform the right IN operand which should be an Item_in_subselect or a
 
1665
    subclass of it. The left operand of the IN must be the same as the left
 
1666
    operand of this Item_in_optimizer, so in this case there is no further
 
1667
    transformation, we only make both operands the same.
 
1668
    TODO: is it the way it should be?
 
1669
  */
 
1670
  DBUG_ASSERT((args[1])->type() == Item::SUBSELECT_ITEM &&
 
1671
              (((Item_subselect*)(args[1]))->substype() ==
 
1672
               Item_subselect::IN_SUBS ||
 
1673
               ((Item_subselect*)(args[1]))->substype() ==
 
1674
               Item_subselect::ALL_SUBS ||
 
1675
               ((Item_subselect*)(args[1]))->substype() ==
 
1676
               Item_subselect::ANY_SUBS));
 
1677
 
 
1678
  Item_in_subselect *in_arg= (Item_in_subselect*)args[1];
 
1679
  in_arg->left_expr= args[0];
 
1680
 
 
1681
  return (this->*transformer)(argument);
 
1682
}
 
1683
 
 
1684
 
 
1685
 
 
1686
longlong Item_func_eq::val_int()
 
1687
{
 
1688
  DBUG_ASSERT(fixed == 1);
 
1689
  int value= cmp.compare();
 
1690
  return value == 0 ? 1 : 0;
 
1691
}
 
1692
 
 
1693
 
 
1694
/** Same as Item_func_eq, but NULL = NULL. */
 
1695
 
 
1696
void Item_func_equal::fix_length_and_dec()
 
1697
{
 
1698
  Item_bool_func2::fix_length_and_dec();
 
1699
  maybe_null=null_value=0;
 
1700
}
 
1701
 
 
1702
longlong Item_func_equal::val_int()
 
1703
{
 
1704
  DBUG_ASSERT(fixed == 1);
 
1705
  return cmp.compare();
 
1706
}
 
1707
 
 
1708
longlong Item_func_ne::val_int()
 
1709
{
 
1710
  DBUG_ASSERT(fixed == 1);
 
1711
  int value= cmp.compare();
 
1712
  return value != 0 && !null_value ? 1 : 0;
 
1713
}
 
1714
 
 
1715
 
 
1716
longlong Item_func_ge::val_int()
 
1717
{
 
1718
  DBUG_ASSERT(fixed == 1);
 
1719
  int value= cmp.compare();
 
1720
  return value >= 0 ? 1 : 0;
 
1721
}
 
1722
 
 
1723
 
 
1724
longlong Item_func_gt::val_int()
 
1725
{
 
1726
  DBUG_ASSERT(fixed == 1);
 
1727
  int value= cmp.compare();
 
1728
  return value > 0 ? 1 : 0;
 
1729
}
 
1730
 
 
1731
longlong Item_func_le::val_int()
 
1732
{
 
1733
  DBUG_ASSERT(fixed == 1);
 
1734
  int value= cmp.compare();
 
1735
  return value <= 0 && !null_value ? 1 : 0;
 
1736
}
 
1737
 
 
1738
 
 
1739
longlong Item_func_lt::val_int()
 
1740
{
 
1741
  DBUG_ASSERT(fixed == 1);
 
1742
  int value= cmp.compare();
 
1743
  return value < 0 && !null_value ? 1 : 0;
 
1744
}
 
1745
 
 
1746
 
 
1747
longlong Item_func_strcmp::val_int()
 
1748
{
 
1749
  DBUG_ASSERT(fixed == 1);
 
1750
  String *a=args[0]->val_str(&tmp_value1);
 
1751
  String *b=args[1]->val_str(&tmp_value2);
 
1752
  if (!a || !b)
 
1753
  {
 
1754
    null_value=1;
 
1755
    return 0;
 
1756
  }
 
1757
  int value= sortcmp(a,b,cmp.cmp_collation.collation);
 
1758
  null_value=0;
 
1759
  return !value ? 0 : (value < 0 ? (longlong) -1 : (longlong) 1);
 
1760
}
 
1761
 
 
1762
 
 
1763
bool Item_func_opt_neg::eq(const Item *item, bool binary_cmp) const
 
1764
{
 
1765
  /* Assume we don't have rtti */
 
1766
  if (this == item)
 
1767
    return 1;
 
1768
  if (item->type() != FUNC_ITEM)
 
1769
    return 0;
 
1770
  Item_func *item_func=(Item_func*) item;
 
1771
  if (arg_count != item_func->arg_count ||
 
1772
      functype() != item_func->functype())
 
1773
    return 0;
 
1774
  if (negated != ((Item_func_opt_neg *) item_func)->negated)
 
1775
    return 0;
 
1776
  for (uint i=0; i < arg_count ; i++)
 
1777
    if (!args[i]->eq(item_func->arguments()[i], binary_cmp))
 
1778
      return 0;
 
1779
  return 1;
 
1780
}
 
1781
 
 
1782
 
 
1783
void Item_func_interval::fix_length_and_dec()
 
1784
{
 
1785
  uint rows= row->cols();
 
1786
  
 
1787
  use_decimal_comparison= ((row->element_index(0)->result_type() ==
 
1788
                            DECIMAL_RESULT) ||
 
1789
                           (row->element_index(0)->result_type() ==
 
1790
                            INT_RESULT));
 
1791
  if (rows > 8)
 
1792
  {
 
1793
    bool not_null_consts= TRUE;
 
1794
 
 
1795
    for (uint i= 1; not_null_consts && i < rows; i++)
 
1796
    {
 
1797
      Item *el= row->element_index(i);
 
1798
      not_null_consts&= el->const_item() & !el->is_null();
 
1799
    }
 
1800
 
 
1801
    if (not_null_consts &&
 
1802
        (intervals=
 
1803
          (interval_range*) sql_alloc(sizeof(interval_range) * (rows - 1))))
 
1804
    {
 
1805
      if (use_decimal_comparison)
 
1806
      {
 
1807
        for (uint i= 1; i < rows; i++)
 
1808
        {
 
1809
          Item *el= row->element_index(i);
 
1810
          interval_range *range= intervals + (i-1);
 
1811
          if ((el->result_type() == DECIMAL_RESULT) ||
 
1812
              (el->result_type() == INT_RESULT))
 
1813
          {
 
1814
            range->type= DECIMAL_RESULT;
 
1815
            range->dec.init();
 
1816
            my_decimal *dec= el->val_decimal(&range->dec);
 
1817
            if (dec != &range->dec)
 
1818
            {
 
1819
              range->dec= *dec;
 
1820
              range->dec.fix_buffer_pointer();
 
1821
            }
 
1822
          }
 
1823
          else
 
1824
          {
 
1825
            range->type= REAL_RESULT;
 
1826
            range->dbl= el->val_real();
 
1827
          }
 
1828
        }
 
1829
      }
 
1830
      else
 
1831
      {
 
1832
        for (uint i= 1; i < rows; i++)
 
1833
        {
 
1834
          intervals[i-1].dbl= row->element_index(i)->val_real();
 
1835
        }
 
1836
      }
 
1837
    }
 
1838
  }
 
1839
  maybe_null= 0;
 
1840
  max_length= 2;
 
1841
  used_tables_cache|= row->used_tables();
 
1842
  not_null_tables_cache= row->not_null_tables();
 
1843
  with_sum_func= with_sum_func || row->with_sum_func;
 
1844
  const_item_cache&= row->const_item();
 
1845
}
 
1846
 
 
1847
 
 
1848
/**
 
1849
  Execute Item_func_interval().
 
1850
 
 
1851
  @note
 
1852
    If we are doing a decimal comparison, we are evaluating the first
 
1853
    item twice.
 
1854
 
 
1855
  @return
 
1856
    - -1 if null value,
 
1857
    - 0 if lower than lowest
 
1858
    - 1 - arg_count-1 if between args[n] and args[n+1]
 
1859
    - arg_count if higher than biggest argument
 
1860
*/
 
1861
 
 
1862
longlong Item_func_interval::val_int()
 
1863
{
 
1864
  DBUG_ASSERT(fixed == 1);
 
1865
  double value;
 
1866
  my_decimal dec_buf, *dec= NULL;
 
1867
  uint i;
 
1868
 
 
1869
  if (use_decimal_comparison)
 
1870
  {
 
1871
    dec= row->element_index(0)->val_decimal(&dec_buf);
 
1872
    if (row->element_index(0)->null_value)
 
1873
      return -1;
 
1874
    my_decimal2double(E_DEC_FATAL_ERROR, dec, &value);
 
1875
  }
 
1876
  else
 
1877
  {
 
1878
    value= row->element_index(0)->val_real();
 
1879
    if (row->element_index(0)->null_value)
 
1880
      return -1;
 
1881
  }
 
1882
 
 
1883
  if (intervals)
 
1884
  {                                     // Use binary search to find interval
 
1885
    uint start,end;
 
1886
    start= 0;
 
1887
    end=   row->cols()-2;
 
1888
    while (start != end)
 
1889
    {
 
1890
      uint mid= (start + end + 1) / 2;
 
1891
      interval_range *range= intervals + mid;
 
1892
      my_bool cmp_result;
 
1893
      /*
 
1894
        The values in the range intervall may have different types,
 
1895
        Only do a decimal comparision of the first argument is a decimal
 
1896
        and we are comparing against a decimal
 
1897
      */
 
1898
      if (dec && range->type == DECIMAL_RESULT)
 
1899
        cmp_result= my_decimal_cmp(&range->dec, dec) <= 0;
 
1900
      else
 
1901
        cmp_result= (range->dbl <= value);
 
1902
      if (cmp_result)
 
1903
        start= mid;
 
1904
      else
 
1905
        end= mid - 1;
 
1906
    }
 
1907
    interval_range *range= intervals+start;
 
1908
    return ((dec && range->type == DECIMAL_RESULT) ?
 
1909
            my_decimal_cmp(dec, &range->dec) < 0 :
 
1910
            value < range->dbl) ? 0 : start + 1;
 
1911
  }
 
1912
 
 
1913
  for (i=1 ; i < row->cols() ; i++)
 
1914
  {
 
1915
    Item *el= row->element_index(i);
 
1916
    if (use_decimal_comparison &&
 
1917
        ((el->result_type() == DECIMAL_RESULT) ||
 
1918
         (el->result_type() == INT_RESULT)))
 
1919
    {
 
1920
      my_decimal e_dec_buf, *e_dec= el->val_decimal(&e_dec_buf);
 
1921
      /* Skip NULL ranges. */
 
1922
      if (el->null_value)
 
1923
        continue;
 
1924
      if (my_decimal_cmp(e_dec, dec) > 0)
 
1925
        return i - 1;
 
1926
    }
 
1927
    else 
 
1928
    {
 
1929
      double val= el->val_real();
 
1930
      /* Skip NULL ranges. */
 
1931
      if (el->null_value)
 
1932
        continue;
 
1933
      if (val > value)
 
1934
        return i - 1;
 
1935
    }
 
1936
  }
 
1937
  return i-1;
 
1938
}
 
1939
 
 
1940
 
 
1941
/**
 
1942
  Perform context analysis of a BETWEEN item tree.
 
1943
 
 
1944
    This function performs context analysis (name resolution) and calculates
 
1945
    various attributes of the item tree with Item_func_between as its root.
 
1946
    The function saves in ref the pointer to the item or to a newly created
 
1947
    item that is considered as a replacement for the original one.
 
1948
 
 
1949
  @param thd     reference to the global context of the query thread
 
1950
  @param ref     pointer to Item* variable where pointer to resulting "fixed"
 
1951
                 item is to be assigned
 
1952
 
 
1953
  @note
 
1954
    Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
 
1955
    a predicate/function level. Then it's easy to show that:
 
1956
    @verbatim
 
1957
      T0(e BETWEEN e1 AND e2)     = union(T1(e),T1(e1),T1(e2))
 
1958
      T1(e BETWEEN e1 AND e2)     = union(T1(e),intersection(T1(e1),T1(e2)))
 
1959
      T0(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
 
1960
      T1(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
 
1961
    @endverbatim
 
1962
 
 
1963
  @retval
 
1964
    0   ok
 
1965
  @retval
 
1966
    1   got error
 
1967
*/
 
1968
 
 
1969
bool Item_func_between::fix_fields(THD *thd, Item **ref)
 
1970
{
 
1971
  if (Item_func_opt_neg::fix_fields(thd, ref))
 
1972
    return 1;
 
1973
 
 
1974
  thd->lex->current_select->between_count++;
 
1975
 
 
1976
  /* not_null_tables_cache == union(T1(e),T1(e1),T1(e2)) */
 
1977
  if (pred_level && !negated)
 
1978
    return 0;
 
1979
 
 
1980
  /* not_null_tables_cache == union(T1(e), intersection(T1(e1),T1(e2))) */
 
1981
  not_null_tables_cache= (args[0]->not_null_tables() |
 
1982
                          (args[1]->not_null_tables() &
 
1983
                           args[2]->not_null_tables()));
 
1984
 
 
1985
  return 0;
 
1986
}
 
1987
 
 
1988
 
 
1989
void Item_func_between::fix_length_and_dec()
 
1990
{
 
1991
  max_length= 1;
 
1992
  int i;
 
1993
  bool datetime_found= FALSE;
 
1994
  int time_items_found= 0;
 
1995
  compare_as_dates= TRUE;
 
1996
  THD *thd= current_thd;
 
1997
 
 
1998
  /*
 
1999
    As some compare functions are generated after sql_yacc,
 
2000
    we have to check for out of memory conditions here
 
2001
  */
 
2002
  if (!args[0] || !args[1] || !args[2])
 
2003
    return;
 
2004
  if ( agg_cmp_type(&cmp_type, args, 3))
 
2005
    return;
 
2006
  if (cmp_type == STRING_RESULT &&
 
2007
      agg_arg_charsets(cmp_collation, args, 3, MY_COLL_CMP_CONV, 1))
 
2008
   return;
 
2009
 
 
2010
  /*
 
2011
    Detect the comparison of DATE/DATETIME items.
 
2012
    At least one of items should be a DATE/DATETIME item and other items
 
2013
    should return the STRING result.
 
2014
  */
 
2015
  if (cmp_type == STRING_RESULT)
 
2016
  {
 
2017
    for (i= 0; i < 3; i++)
 
2018
    {
 
2019
      if (args[i]->is_datetime())
 
2020
      {
 
2021
        datetime_found= TRUE;
 
2022
        continue;
 
2023
      }
 
2024
      if (args[i]->field_type() == MYSQL_TYPE_TIME &&
 
2025
          args[i]->result_as_longlong())
 
2026
        time_items_found++;
 
2027
    }
 
2028
  }
 
2029
  if (!datetime_found)
 
2030
    compare_as_dates= FALSE;
 
2031
 
 
2032
  if (compare_as_dates)
 
2033
  {
 
2034
    ge_cmp.set_datetime_cmp_func(args, args + 1);
 
2035
    le_cmp.set_datetime_cmp_func(args, args + 2);
 
2036
  }
 
2037
  else if (time_items_found == 3)
 
2038
  {
 
2039
    /* Compare TIME items as integers. */
 
2040
    cmp_type= INT_RESULT;
 
2041
  }
 
2042
  else if (args[0]->real_item()->type() == FIELD_ITEM &&
 
2043
           thd->lex->sql_command != SQLCOM_SHOW_CREATE)
 
2044
  {
 
2045
    Item_field *field_item= (Item_field*) (args[0]->real_item());
 
2046
    if (field_item->field->can_be_compared_as_longlong())
 
2047
    {
 
2048
      /*
 
2049
        The following can't be recoded with || as convert_constant_item
 
2050
        changes the argument
 
2051
      */
 
2052
      if (convert_constant_item(thd, field_item, &args[1]))
 
2053
        cmp_type=INT_RESULT;                    // Works for all types.
 
2054
      if (convert_constant_item(thd, field_item, &args[2]))
 
2055
        cmp_type=INT_RESULT;                    // Works for all types.
 
2056
    }
 
2057
  }
 
2058
}
 
2059
 
 
2060
 
 
2061
longlong Item_func_between::val_int()
 
2062
{                                               // ANSI BETWEEN
 
2063
  DBUG_ASSERT(fixed == 1);
 
2064
  if (compare_as_dates)
 
2065
  {
 
2066
    int ge_res, le_res;
 
2067
 
 
2068
    ge_res= ge_cmp.compare();
 
2069
    if ((null_value= args[0]->null_value))
 
2070
      return 0;
 
2071
    le_res= le_cmp.compare();
 
2072
 
 
2073
    if (!args[1]->null_value && !args[2]->null_value)
 
2074
      return (longlong) ((ge_res >= 0 && le_res <=0) != negated);
 
2075
    else if (args[1]->null_value)
 
2076
    {
 
2077
      null_value= le_res > 0;                   // not null if false range.
 
2078
    }
 
2079
    else
 
2080
    {
 
2081
      null_value= ge_res < 0;
 
2082
    }
 
2083
  }
 
2084
  else if (cmp_type == STRING_RESULT)
 
2085
  {
 
2086
    String *value,*a,*b;
 
2087
    value=args[0]->val_str(&value0);
 
2088
    if ((null_value=args[0]->null_value))
 
2089
      return 0;
 
2090
    a=args[1]->val_str(&value1);
 
2091
    b=args[2]->val_str(&value2);
 
2092
    if (!args[1]->null_value && !args[2]->null_value)
 
2093
      return (longlong) ((sortcmp(value,a,cmp_collation.collation) >= 0 &&
 
2094
                          sortcmp(value,b,cmp_collation.collation) <= 0) !=
 
2095
                         negated);
 
2096
    if (args[1]->null_value && args[2]->null_value)
 
2097
      null_value=1;
 
2098
    else if (args[1]->null_value)
 
2099
    {
 
2100
      // Set to not null if false range.
 
2101
      null_value= sortcmp(value,b,cmp_collation.collation) <= 0;
 
2102
    }
 
2103
    else
 
2104
    {
 
2105
      // Set to not null if false range.
 
2106
      null_value= sortcmp(value,a,cmp_collation.collation) >= 0;
 
2107
    }
 
2108
  }
 
2109
  else if (cmp_type == INT_RESULT)
 
2110
  {
 
2111
    longlong value=args[0]->val_int(), a, b;
 
2112
    if ((null_value=args[0]->null_value))
 
2113
      return 0;                                 /* purecov: inspected */
 
2114
    a=args[1]->val_int();
 
2115
    b=args[2]->val_int();
 
2116
    if (!args[1]->null_value && !args[2]->null_value)
 
2117
      return (longlong) ((value >= a && value <= b) != negated);
 
2118
    if (args[1]->null_value && args[2]->null_value)
 
2119
      null_value=1;
 
2120
    else if (args[1]->null_value)
 
2121
    {
 
2122
      null_value= value <= b;                   // not null if false range.
 
2123
    }
 
2124
    else
 
2125
    {
 
2126
      null_value= value >= a;
 
2127
    }
 
2128
  }
 
2129
  else if (cmp_type == DECIMAL_RESULT)
 
2130
  {
 
2131
    my_decimal dec_buf, *dec= args[0]->val_decimal(&dec_buf),
 
2132
               a_buf, *a_dec, b_buf, *b_dec;
 
2133
    if ((null_value=args[0]->null_value))
 
2134
      return 0;                                 /* purecov: inspected */
 
2135
    a_dec= args[1]->val_decimal(&a_buf);
 
2136
    b_dec= args[2]->val_decimal(&b_buf);
 
2137
    if (!args[1]->null_value && !args[2]->null_value)
 
2138
      return (longlong) ((my_decimal_cmp(dec, a_dec) >= 0 &&
 
2139
                          my_decimal_cmp(dec, b_dec) <= 0) != negated);
 
2140
    if (args[1]->null_value && args[2]->null_value)
 
2141
      null_value=1;
 
2142
    else if (args[1]->null_value)
 
2143
      null_value= (my_decimal_cmp(dec, b_dec) <= 0);
 
2144
    else
 
2145
      null_value= (my_decimal_cmp(dec, a_dec) >= 0);
 
2146
  }
 
2147
  else
 
2148
  {
 
2149
    double value= args[0]->val_real(),a,b;
 
2150
    if ((null_value=args[0]->null_value))
 
2151
      return 0;                                 /* purecov: inspected */
 
2152
    a= args[1]->val_real();
 
2153
    b= args[2]->val_real();
 
2154
    if (!args[1]->null_value && !args[2]->null_value)
 
2155
      return (longlong) ((value >= a && value <= b) != negated);
 
2156
    if (args[1]->null_value && args[2]->null_value)
 
2157
      null_value=1;
 
2158
    else if (args[1]->null_value)
 
2159
    {
 
2160
      null_value= value <= b;                   // not null if false range.
 
2161
    }
 
2162
    else
 
2163
    {
 
2164
      null_value= value >= a;
 
2165
    }
 
2166
  }
 
2167
  return (longlong) (!null_value && negated);
 
2168
}
 
2169
 
 
2170
 
 
2171
void Item_func_between::print(String *str, enum_query_type query_type)
 
2172
{
 
2173
  str->append('(');
 
2174
  args[0]->print(str, query_type);
 
2175
  if (negated)
 
2176
    str->append(STRING_WITH_LEN(" not"));
 
2177
  str->append(STRING_WITH_LEN(" between "));
 
2178
  args[1]->print(str, query_type);
 
2179
  str->append(STRING_WITH_LEN(" and "));
 
2180
  args[2]->print(str, query_type);
 
2181
  str->append(')');
 
2182
}
 
2183
 
 
2184
void
 
2185
Item_func_ifnull::fix_length_and_dec()
 
2186
{
 
2187
  agg_result_type(&hybrid_type, args, 2);
 
2188
  maybe_null=args[1]->maybe_null;
 
2189
  decimals= max(args[0]->decimals, args[1]->decimals);
 
2190
  unsigned_flag= args[0]->unsigned_flag && args[1]->unsigned_flag;
 
2191
 
 
2192
  if (hybrid_type == DECIMAL_RESULT || hybrid_type == INT_RESULT) 
 
2193
  {
 
2194
    int len0= args[0]->max_length - args[0]->decimals
 
2195
      - (args[0]->unsigned_flag ? 0 : 1);
 
2196
 
 
2197
    int len1= args[1]->max_length - args[1]->decimals
 
2198
      - (args[1]->unsigned_flag ? 0 : 1);
 
2199
 
 
2200
    max_length= max(len0, len1) + decimals + (unsigned_flag ? 0 : 1);
 
2201
  }
 
2202
  else
 
2203
    max_length= max(args[0]->max_length, args[1]->max_length);
 
2204
 
 
2205
  switch (hybrid_type) {
 
2206
  case STRING_RESULT:
 
2207
    agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1);
 
2208
    break;
 
2209
  case DECIMAL_RESULT:
 
2210
  case REAL_RESULT:
 
2211
    break;
 
2212
  case INT_RESULT:
 
2213
    decimals= 0;
 
2214
    break;
 
2215
  case ROW_RESULT:
 
2216
  default:
 
2217
    DBUG_ASSERT(0);
 
2218
  }
 
2219
  cached_field_type= agg_field_type(args, 2);
 
2220
}
 
2221
 
 
2222
 
 
2223
uint Item_func_ifnull::decimal_precision() const
 
2224
{
 
2225
  int max_int_part=max(args[0]->decimal_int_part(),args[1]->decimal_int_part());
 
2226
  return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
 
2227
}
 
2228
 
 
2229
 
 
2230
enum_field_types Item_func_ifnull::field_type() const 
 
2231
{
 
2232
  return cached_field_type;
 
2233
}
 
2234
 
 
2235
Field *Item_func_ifnull::tmp_table_field(TABLE *table)
 
2236
{
 
2237
  return tmp_table_field_from_field_type(table, 0);
 
2238
}
 
2239
 
 
2240
double
 
2241
Item_func_ifnull::real_op()
 
2242
{
 
2243
  DBUG_ASSERT(fixed == 1);
 
2244
  double value= args[0]->val_real();
 
2245
  if (!args[0]->null_value)
 
2246
  {
 
2247
    null_value=0;
 
2248
    return value;
 
2249
  }
 
2250
  value= args[1]->val_real();
 
2251
  if ((null_value=args[1]->null_value))
 
2252
    return 0.0;
 
2253
  return value;
 
2254
}
 
2255
 
 
2256
longlong
 
2257
Item_func_ifnull::int_op()
 
2258
{
 
2259
  DBUG_ASSERT(fixed == 1);
 
2260
  longlong value=args[0]->val_int();
 
2261
  if (!args[0]->null_value)
 
2262
  {
 
2263
    null_value=0;
 
2264
    return value;
 
2265
  }
 
2266
  value=args[1]->val_int();
 
2267
  if ((null_value=args[1]->null_value))
 
2268
    return 0;
 
2269
  return value;
 
2270
}
 
2271
 
 
2272
 
 
2273
my_decimal *Item_func_ifnull::decimal_op(my_decimal *decimal_value)
 
2274
{
 
2275
  DBUG_ASSERT(fixed == 1);
 
2276
  my_decimal *value= args[0]->val_decimal(decimal_value);
 
2277
  if (!args[0]->null_value)
 
2278
  {
 
2279
    null_value= 0;
 
2280
    return value;
 
2281
  }
 
2282
  value= args[1]->val_decimal(decimal_value);
 
2283
  if ((null_value= args[1]->null_value))
 
2284
    return 0;
 
2285
  return value;
 
2286
}
 
2287
 
 
2288
 
 
2289
String *
 
2290
Item_func_ifnull::str_op(String *str)
 
2291
{
 
2292
  DBUG_ASSERT(fixed == 1);
 
2293
  String *res  =args[0]->val_str(str);
 
2294
  if (!args[0]->null_value)
 
2295
  {
 
2296
    null_value=0;
 
2297
    res->set_charset(collation.collation);
 
2298
    return res;
 
2299
  }
 
2300
  res=args[1]->val_str(str);
 
2301
  if ((null_value=args[1]->null_value))
 
2302
    return 0;
 
2303
  res->set_charset(collation.collation);
 
2304
  return res;
 
2305
}
 
2306
 
 
2307
 
 
2308
/**
 
2309
  Perform context analysis of an IF item tree.
 
2310
 
 
2311
    This function performs context analysis (name resolution) and calculates
 
2312
    various attributes of the item tree with Item_func_if as its root.
 
2313
    The function saves in ref the pointer to the item or to a newly created
 
2314
    item that is considered as a replacement for the original one.
 
2315
 
 
2316
  @param thd     reference to the global context of the query thread
 
2317
  @param ref     pointer to Item* variable where pointer to resulting "fixed"
 
2318
                 item is to be assigned
 
2319
 
 
2320
  @note
 
2321
    Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
 
2322
    a predicate/function level. Then it's easy to show that:
 
2323
    @verbatim
 
2324
      T0(IF(e,e1,e2)  = T1(IF(e,e1,e2))
 
2325
      T1(IF(e,e1,e2)) = intersection(T1(e1),T1(e2))
 
2326
    @endverbatim
 
2327
 
 
2328
  @retval
 
2329
    0   ok
 
2330
  @retval
 
2331
    1   got error
 
2332
*/
 
2333
 
 
2334
bool
 
2335
Item_func_if::fix_fields(THD *thd, Item **ref)
 
2336
{
 
2337
  DBUG_ASSERT(fixed == 0);
 
2338
  args[0]->top_level_item();
 
2339
 
 
2340
  if (Item_func::fix_fields(thd, ref))
 
2341
    return 1;
 
2342
 
 
2343
  not_null_tables_cache= (args[1]->not_null_tables() &
 
2344
                          args[2]->not_null_tables());
 
2345
 
 
2346
  return 0;
 
2347
}
 
2348
 
 
2349
 
 
2350
void
 
2351
Item_func_if::fix_length_and_dec()
 
2352
{
 
2353
  maybe_null=args[1]->maybe_null || args[2]->maybe_null;
 
2354
  decimals= max(args[1]->decimals, args[2]->decimals);
 
2355
  unsigned_flag=args[1]->unsigned_flag && args[2]->unsigned_flag;
 
2356
 
 
2357
  enum Item_result arg1_type=args[1]->result_type();
 
2358
  enum Item_result arg2_type=args[2]->result_type();
 
2359
  bool null1=args[1]->const_item() && args[1]->null_value;
 
2360
  bool null2=args[2]->const_item() && args[2]->null_value;
 
2361
 
 
2362
  if (null1)
 
2363
  {
 
2364
    cached_result_type= arg2_type;
 
2365
    collation.set(args[2]->collation.collation);
 
2366
    cached_field_type= args[2]->field_type();
 
2367
  }
 
2368
  else if (null2)
 
2369
  {
 
2370
    cached_result_type= arg1_type;
 
2371
    collation.set(args[1]->collation.collation);
 
2372
    cached_field_type= args[1]->field_type();
 
2373
  }
 
2374
  else
 
2375
  {
 
2376
    agg_result_type(&cached_result_type, args+1, 2);
 
2377
    if (cached_result_type == STRING_RESULT)
 
2378
    {
 
2379
      if (agg_arg_charsets(collation, args+1, 2, MY_COLL_ALLOW_CONV, 1))
 
2380
        return;
 
2381
    }
 
2382
    else
 
2383
    {
 
2384
      collation.set(&my_charset_bin);   // Number
 
2385
    }
 
2386
    cached_field_type= agg_field_type(args + 1, 2);
 
2387
  }
 
2388
 
 
2389
  if ((cached_result_type == DECIMAL_RESULT )
 
2390
      || (cached_result_type == INT_RESULT))
 
2391
  {
 
2392
    int len1= args[1]->max_length - args[1]->decimals
 
2393
      - (args[1]->unsigned_flag ? 0 : 1);
 
2394
 
 
2395
    int len2= args[2]->max_length - args[2]->decimals
 
2396
      - (args[2]->unsigned_flag ? 0 : 1);
 
2397
 
 
2398
    max_length=max(len1, len2) + decimals + (unsigned_flag ? 0 : 1);
 
2399
  }
 
2400
  else
 
2401
    max_length= max(args[1]->max_length, args[2]->max_length);
 
2402
}
 
2403
 
 
2404
 
 
2405
uint Item_func_if::decimal_precision() const
 
2406
{
 
2407
  int precision=(max(args[1]->decimal_int_part(),args[2]->decimal_int_part())+
 
2408
                 decimals);
 
2409
  return min(precision, DECIMAL_MAX_PRECISION);
 
2410
}
 
2411
 
 
2412
 
 
2413
double
 
2414
Item_func_if::val_real()
 
2415
{
 
2416
  DBUG_ASSERT(fixed == 1);
 
2417
  Item *arg= args[0]->val_bool() ? args[1] : args[2];
 
2418
  double value= arg->val_real();
 
2419
  null_value=arg->null_value;
 
2420
  return value;
 
2421
}
 
2422
 
 
2423
longlong
 
2424
Item_func_if::val_int()
 
2425
{
 
2426
  DBUG_ASSERT(fixed == 1);
 
2427
  Item *arg= args[0]->val_bool() ? args[1] : args[2];
 
2428
  longlong value=arg->val_int();
 
2429
  null_value=arg->null_value;
 
2430
  return value;
 
2431
}
 
2432
 
 
2433
String *
 
2434
Item_func_if::val_str(String *str)
 
2435
{
 
2436
  DBUG_ASSERT(fixed == 1);
 
2437
  Item *arg= args[0]->val_bool() ? args[1] : args[2];
 
2438
  String *res=arg->val_str(str);
 
2439
  if (res)
 
2440
    res->set_charset(collation.collation);
 
2441
  null_value=arg->null_value;
 
2442
  return res;
 
2443
}
 
2444
 
 
2445
 
 
2446
my_decimal *
 
2447
Item_func_if::val_decimal(my_decimal *decimal_value)
 
2448
{
 
2449
  DBUG_ASSERT(fixed == 1);
 
2450
  Item *arg= args[0]->val_bool() ? args[1] : args[2];
 
2451
  my_decimal *value= arg->val_decimal(decimal_value);
 
2452
  null_value= arg->null_value;
 
2453
  return value;
 
2454
}
 
2455
 
 
2456
 
 
2457
void
 
2458
Item_func_nullif::fix_length_and_dec()
 
2459
{
 
2460
  Item_bool_func2::fix_length_and_dec();
 
2461
  maybe_null=1;
 
2462
  if (args[0])                                  // Only false if EOM
 
2463
  {
 
2464
    max_length=args[0]->max_length;
 
2465
    decimals=args[0]->decimals;
 
2466
    unsigned_flag= args[0]->unsigned_flag;
 
2467
    cached_result_type= args[0]->result_type();
 
2468
    if (cached_result_type == STRING_RESULT &&
 
2469
        agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1))
 
2470
      return;
 
2471
  }
 
2472
}
 
2473
 
 
2474
 
 
2475
/**
 
2476
  @note
 
2477
  Note that we have to evaluate the first argument twice as the compare
 
2478
  may have been done with a different type than return value
 
2479
  @return
 
2480
    NULL  if arguments are equal
 
2481
  @return
 
2482
    the first argument if not equal
 
2483
*/
 
2484
 
 
2485
double
 
2486
Item_func_nullif::val_real()
 
2487
{
 
2488
  DBUG_ASSERT(fixed == 1);
 
2489
  double value;
 
2490
  if (!cmp.compare())
 
2491
  {
 
2492
    null_value=1;
 
2493
    return 0.0;
 
2494
  }
 
2495
  value= args[0]->val_real();
 
2496
  null_value=args[0]->null_value;
 
2497
  return value;
 
2498
}
 
2499
 
 
2500
longlong
 
2501
Item_func_nullif::val_int()
 
2502
{
 
2503
  DBUG_ASSERT(fixed == 1);
 
2504
  longlong value;
 
2505
  if (!cmp.compare())
 
2506
  {
 
2507
    null_value=1;
 
2508
    return 0;
 
2509
  }
 
2510
  value=args[0]->val_int();
 
2511
  null_value=args[0]->null_value;
 
2512
  return value;
 
2513
}
 
2514
 
 
2515
String *
 
2516
Item_func_nullif::val_str(String *str)
 
2517
{
 
2518
  DBUG_ASSERT(fixed == 1);
 
2519
  String *res;
 
2520
  if (!cmp.compare())
 
2521
  {
 
2522
    null_value=1;
 
2523
    return 0;
 
2524
  }
 
2525
  res=args[0]->val_str(str);
 
2526
  null_value=args[0]->null_value;
 
2527
  return res;
 
2528
}
 
2529
 
 
2530
 
 
2531
my_decimal *
 
2532
Item_func_nullif::val_decimal(my_decimal * decimal_value)
 
2533
{
 
2534
  DBUG_ASSERT(fixed == 1);
 
2535
  my_decimal *res;
 
2536
  if (!cmp.compare())
 
2537
  {
 
2538
    null_value=1;
 
2539
    return 0;
 
2540
  }
 
2541
  res= args[0]->val_decimal(decimal_value);
 
2542
  null_value= args[0]->null_value;
 
2543
  return res;
 
2544
}
 
2545
 
 
2546
 
 
2547
bool
 
2548
Item_func_nullif::is_null()
 
2549
{
 
2550
  return (null_value= (!cmp.compare() ? 1 : args[0]->null_value)); 
 
2551
}
 
2552
 
 
2553
 
 
2554
/**
 
2555
    Find and return matching items for CASE or ELSE item if all compares
 
2556
    are failed or NULL if ELSE item isn't defined.
 
2557
 
 
2558
  IMPLEMENTATION
 
2559
    In order to do correct comparisons of the CASE expression (the expression
 
2560
    between CASE and the first WHEN) with each WHEN expression several
 
2561
    comparators are used. One for each result type. CASE expression can be
 
2562
    evaluated up to # of different result types are used. To check whether
 
2563
    the CASE expression already was evaluated for a particular result type
 
2564
    a bit mapped variable value_added_map is used. Result types are mapped
 
2565
    to it according to their int values i.e. STRING_RESULT is mapped to bit
 
2566
    0, REAL_RESULT to bit 1, so on.
 
2567
 
 
2568
  @retval
 
2569
    NULL  Nothing found and there is no ELSE expression defined
 
2570
  @retval
 
2571
    item  Found item or ELSE item if defined and all comparisons are
 
2572
           failed
 
2573
*/
 
2574
 
 
2575
Item *Item_func_case::find_item(String *str)
 
2576
{
 
2577
  uint value_added_map= 0;
 
2578
 
 
2579
  if (first_expr_num == -1)
 
2580
  {
 
2581
    for (uint i=0 ; i < ncases ; i+=2)
 
2582
    {
 
2583
      // No expression between CASE and the first WHEN
 
2584
      if (args[i]->val_bool())
 
2585
        return args[i+1];
 
2586
      continue;
 
2587
    }
 
2588
  }
 
2589
  else
 
2590
  {
 
2591
    /* Compare every WHEN argument with it and return the first match */
 
2592
    for (uint i=0 ; i < ncases ; i+=2)
 
2593
    {
 
2594
      cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
 
2595
      DBUG_ASSERT(cmp_type != ROW_RESULT);
 
2596
      DBUG_ASSERT(cmp_items[(uint)cmp_type]);
 
2597
      if (!(value_added_map & (1<<(uint)cmp_type)))
 
2598
      {
 
2599
        cmp_items[(uint)cmp_type]->store_value(args[first_expr_num]);
 
2600
        if ((null_value=args[first_expr_num]->null_value))
 
2601
          return else_expr_num != -1 ? args[else_expr_num] : 0;
 
2602
        value_added_map|= 1<<(uint)cmp_type;
 
2603
      }
 
2604
      if (!cmp_items[(uint)cmp_type]->cmp(args[i]) && !args[i]->null_value)
 
2605
        return args[i + 1];
 
2606
    }
 
2607
  }
 
2608
  // No, WHEN clauses all missed, return ELSE expression
 
2609
  return else_expr_num != -1 ? args[else_expr_num] : 0;
 
2610
}
 
2611
 
 
2612
 
 
2613
String *Item_func_case::val_str(String *str)
 
2614
{
 
2615
  DBUG_ASSERT(fixed == 1);
 
2616
  String *res;
 
2617
  Item *item=find_item(str);
 
2618
 
 
2619
  if (!item)
 
2620
  {
 
2621
    null_value=1;
 
2622
    return 0;
 
2623
  }
 
2624
  null_value= 0;
 
2625
  if (!(res=item->val_str(str)))
 
2626
    null_value= 1;
 
2627
  return res;
 
2628
}
 
2629
 
 
2630
 
 
2631
longlong Item_func_case::val_int()
 
2632
{
 
2633
  DBUG_ASSERT(fixed == 1);
 
2634
  char buff[MAX_FIELD_WIDTH];
 
2635
  String dummy_str(buff,sizeof(buff),default_charset());
 
2636
  Item *item=find_item(&dummy_str);
 
2637
  longlong res;
 
2638
 
 
2639
  if (!item)
 
2640
  {
 
2641
    null_value=1;
 
2642
    return 0;
 
2643
  }
 
2644
  res=item->val_int();
 
2645
  null_value=item->null_value;
 
2646
  return res;
 
2647
}
 
2648
 
 
2649
double Item_func_case::val_real()
 
2650
{
 
2651
  DBUG_ASSERT(fixed == 1);
 
2652
  char buff[MAX_FIELD_WIDTH];
 
2653
  String dummy_str(buff,sizeof(buff),default_charset());
 
2654
  Item *item=find_item(&dummy_str);
 
2655
  double res;
 
2656
 
 
2657
  if (!item)
 
2658
  {
 
2659
    null_value=1;
 
2660
    return 0;
 
2661
  }
 
2662
  res= item->val_real();
 
2663
  null_value=item->null_value;
 
2664
  return res;
 
2665
}
 
2666
 
 
2667
 
 
2668
my_decimal *Item_func_case::val_decimal(my_decimal *decimal_value)
 
2669
{
 
2670
  DBUG_ASSERT(fixed == 1);
 
2671
  char buff[MAX_FIELD_WIDTH];
 
2672
  String dummy_str(buff, sizeof(buff), default_charset());
 
2673
  Item *item= find_item(&dummy_str);
 
2674
  my_decimal *res;
 
2675
 
 
2676
  if (!item)
 
2677
  {
 
2678
    null_value=1;
 
2679
    return 0;
 
2680
  }
 
2681
 
 
2682
  res= item->val_decimal(decimal_value);
 
2683
  null_value= item->null_value;
 
2684
  return res;
 
2685
}
 
2686
 
 
2687
 
 
2688
bool Item_func_case::fix_fields(THD *thd, Item **ref)
 
2689
{
 
2690
  /*
 
2691
    buff should match stack usage from
 
2692
    Item_func_case::val_int() -> Item_func_case::find_item()
 
2693
  */
 
2694
  uchar buff[MAX_FIELD_WIDTH*2+sizeof(String)*2+sizeof(String*)*2+sizeof(double)*2+sizeof(longlong)*2];
 
2695
  bool res= Item_func::fix_fields(thd, ref);
 
2696
  /*
 
2697
    Call check_stack_overrun after fix_fields to be sure that stack variable
 
2698
    is not optimized away
 
2699
  */
 
2700
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
 
2701
    return TRUE;                                // Fatal error flag is set!
 
2702
  return res;
 
2703
}
 
2704
 
 
2705
 
 
2706
void Item_func_case::agg_str_lengths(Item* arg)
 
2707
{
 
2708
  set_if_bigger(max_length, arg->max_length);
 
2709
  set_if_bigger(decimals, arg->decimals);
 
2710
  unsigned_flag= unsigned_flag && arg->unsigned_flag;
 
2711
}
 
2712
 
 
2713
 
 
2714
void Item_func_case::agg_num_lengths(Item *arg)
 
2715
{
 
2716
  uint len= my_decimal_length_to_precision(arg->max_length, arg->decimals,
 
2717
                                           arg->unsigned_flag) - arg->decimals;
 
2718
  set_if_bigger(max_length, len); 
 
2719
  set_if_bigger(decimals, arg->decimals);
 
2720
  unsigned_flag= unsigned_flag && arg->unsigned_flag; 
 
2721
}
 
2722
 
 
2723
 
 
2724
void Item_func_case::fix_length_and_dec()
 
2725
{
 
2726
  Item **agg;
 
2727
  uint nagg;
 
2728
  uint found_types= 0;
 
2729
  if (!(agg= (Item**) sql_alloc(sizeof(Item*)*(ncases+1))))
 
2730
    return;
 
2731
  
 
2732
  /*
 
2733
    Aggregate all THEN and ELSE expression types
 
2734
    and collations when string result
 
2735
  */
 
2736
  
 
2737
  for (nagg= 0 ; nagg < ncases/2 ; nagg++)
 
2738
    agg[nagg]= args[nagg*2+1];
 
2739
  
 
2740
  if (else_expr_num != -1)
 
2741
    agg[nagg++]= args[else_expr_num];
 
2742
  
 
2743
  agg_result_type(&cached_result_type, agg, nagg);
 
2744
  if ((cached_result_type == STRING_RESULT) &&
 
2745
      agg_arg_charsets(collation, agg, nagg, MY_COLL_ALLOW_CONV, 1))
 
2746
    return;
 
2747
  
 
2748
  cached_field_type= agg_field_type(agg, nagg);
 
2749
  /*
 
2750
    Aggregate first expression and all THEN expression types
 
2751
    and collations when string comparison
 
2752
  */
 
2753
  if (first_expr_num != -1)
 
2754
  {
 
2755
    uint i;
 
2756
    agg[0]= args[first_expr_num];
 
2757
    left_result_type= agg[0]->result_type();
 
2758
 
 
2759
    for (nagg= 0; nagg < ncases/2 ; nagg++)
 
2760
      agg[nagg+1]= args[nagg*2];
 
2761
    nagg++;
 
2762
    if (!(found_types= collect_cmp_types(agg, nagg)))
 
2763
      return;
 
2764
 
 
2765
    for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
 
2766
    {
 
2767
      if (found_types & (1 << i) && !cmp_items[i])
 
2768
      {
 
2769
        DBUG_ASSERT((Item_result)i != ROW_RESULT);
 
2770
        if ((Item_result)i == STRING_RESULT &&
 
2771
            agg_arg_charsets(cmp_collation, agg, nagg, MY_COLL_CMP_CONV, 1))
 
2772
          return;
 
2773
        if (!(cmp_items[i]=
 
2774
            cmp_item::get_comparator((Item_result)i,
 
2775
                                     cmp_collation.collation)))
 
2776
          return;
 
2777
      }
 
2778
    }
 
2779
  }
 
2780
 
 
2781
  if (else_expr_num == -1 || args[else_expr_num]->maybe_null)
 
2782
    maybe_null=1;
 
2783
  
 
2784
  max_length=0;
 
2785
  decimals=0;
 
2786
  unsigned_flag= TRUE;
 
2787
  if (cached_result_type == STRING_RESULT)
 
2788
  {
 
2789
    for (uint i= 0; i < ncases; i+= 2)
 
2790
      agg_str_lengths(args[i + 1]);
 
2791
    if (else_expr_num != -1)
 
2792
      agg_str_lengths(args[else_expr_num]);
 
2793
  }
 
2794
  else
 
2795
  {
 
2796
    for (uint i= 0; i < ncases; i+= 2)
 
2797
      agg_num_lengths(args[i + 1]);
 
2798
    if (else_expr_num != -1) 
 
2799
      agg_num_lengths(args[else_expr_num]);
 
2800
    max_length= my_decimal_precision_to_length(max_length + decimals, decimals,
 
2801
                                               unsigned_flag);
 
2802
  }
 
2803
}
 
2804
 
 
2805
 
 
2806
uint Item_func_case::decimal_precision() const
 
2807
{
 
2808
  int max_int_part=0;
 
2809
  for (uint i=0 ; i < ncases ; i+=2)
 
2810
    set_if_bigger(max_int_part, args[i+1]->decimal_int_part());
 
2811
 
 
2812
  if (else_expr_num != -1) 
 
2813
    set_if_bigger(max_int_part, args[else_expr_num]->decimal_int_part());
 
2814
  return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
 
2815
}
 
2816
 
 
2817
 
 
2818
/**
 
2819
  @todo
 
2820
    Fix this so that it prints the whole CASE expression
 
2821
*/
 
2822
 
 
2823
void Item_func_case::print(String *str, enum_query_type query_type)
 
2824
{
 
2825
  str->append(STRING_WITH_LEN("(case "));
 
2826
  if (first_expr_num != -1)
 
2827
  {
 
2828
    args[first_expr_num]->print(str, query_type);
 
2829
    str->append(' ');
 
2830
  }
 
2831
  for (uint i=0 ; i < ncases ; i+=2)
 
2832
  {
 
2833
    str->append(STRING_WITH_LEN("when "));
 
2834
    args[i]->print(str, query_type);
 
2835
    str->append(STRING_WITH_LEN(" then "));
 
2836
    args[i+1]->print(str, query_type);
 
2837
    str->append(' ');
 
2838
  }
 
2839
  if (else_expr_num != -1)
 
2840
  {
 
2841
    str->append(STRING_WITH_LEN("else "));
 
2842
    args[else_expr_num]->print(str, query_type);
 
2843
    str->append(' ');
 
2844
  }
 
2845
  str->append(STRING_WITH_LEN("end)"));
 
2846
}
 
2847
 
 
2848
 
 
2849
void Item_func_case::cleanup()
 
2850
{
 
2851
  uint i;
 
2852
  DBUG_ENTER("Item_func_case::cleanup");
 
2853
  Item_func::cleanup();
 
2854
  for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
 
2855
  {
 
2856
    delete cmp_items[i];
 
2857
    cmp_items[i]= 0;
 
2858
  }
 
2859
  DBUG_VOID_RETURN;
 
2860
}
 
2861
 
 
2862
 
 
2863
/**
 
2864
  Coalesce - return first not NULL argument.
 
2865
*/
 
2866
 
 
2867
String *Item_func_coalesce::str_op(String *str)
 
2868
{
 
2869
  DBUG_ASSERT(fixed == 1);
 
2870
  null_value=0;
 
2871
  for (uint i=0 ; i < arg_count ; i++)
 
2872
  {
 
2873
    String *res;
 
2874
    if ((res=args[i]->val_str(str)))
 
2875
      return res;
 
2876
  }
 
2877
  null_value=1;
 
2878
  return 0;
 
2879
}
 
2880
 
 
2881
longlong Item_func_coalesce::int_op()
 
2882
{
 
2883
  DBUG_ASSERT(fixed == 1);
 
2884
  null_value=0;
 
2885
  for (uint i=0 ; i < arg_count ; i++)
 
2886
  {
 
2887
    longlong res=args[i]->val_int();
 
2888
    if (!args[i]->null_value)
 
2889
      return res;
 
2890
  }
 
2891
  null_value=1;
 
2892
  return 0;
 
2893
}
 
2894
 
 
2895
double Item_func_coalesce::real_op()
 
2896
{
 
2897
  DBUG_ASSERT(fixed == 1);
 
2898
  null_value=0;
 
2899
  for (uint i=0 ; i < arg_count ; i++)
 
2900
  {
 
2901
    double res= args[i]->val_real();
 
2902
    if (!args[i]->null_value)
 
2903
      return res;
 
2904
  }
 
2905
  null_value=1;
 
2906
  return 0;
 
2907
}
 
2908
 
 
2909
 
 
2910
my_decimal *Item_func_coalesce::decimal_op(my_decimal *decimal_value)
 
2911
{
 
2912
  DBUG_ASSERT(fixed == 1);
 
2913
  null_value= 0;
 
2914
  for (uint i= 0; i < arg_count; i++)
 
2915
  {
 
2916
    my_decimal *res= args[i]->val_decimal(decimal_value);
 
2917
    if (!args[i]->null_value)
 
2918
      return res;
 
2919
  }
 
2920
  null_value=1;
 
2921
  return 0;
 
2922
}
 
2923
 
 
2924
 
 
2925
void Item_func_coalesce::fix_length_and_dec()
 
2926
{
 
2927
  cached_field_type= agg_field_type(args, arg_count);
 
2928
  agg_result_type(&hybrid_type, args, arg_count);
 
2929
  switch (hybrid_type) {
 
2930
  case STRING_RESULT:
 
2931
    count_only_length();
 
2932
    decimals= NOT_FIXED_DEC;
 
2933
    agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1);
 
2934
    break;
 
2935
  case DECIMAL_RESULT:
 
2936
    count_decimal_length();
 
2937
    break;
 
2938
  case REAL_RESULT:
 
2939
    count_real_length();
 
2940
    break;
 
2941
  case INT_RESULT:
 
2942
    count_only_length();
 
2943
    decimals= 0;
 
2944
    break;
 
2945
  case ROW_RESULT:
 
2946
  default:
 
2947
    DBUG_ASSERT(0);
 
2948
  }
 
2949
}
 
2950
 
 
2951
/****************************************************************************
 
2952
 Classes and function for the IN operator
 
2953
****************************************************************************/
 
2954
 
 
2955
/*
 
2956
  Determine which of the signed longlong arguments is bigger
 
2957
 
 
2958
  SYNOPSIS
 
2959
    cmp_longs()
 
2960
      a_val     left argument
 
2961
      b_val     right argument
 
2962
 
 
2963
  DESCRIPTION
 
2964
    This function will compare two signed longlong arguments
 
2965
    and will return -1, 0, or 1 if left argument is smaller than,
 
2966
    equal to or greater than the right argument.
 
2967
 
 
2968
  RETURN VALUE
 
2969
    -1          left argument is smaller than the right argument.
 
2970
    0           left argument is equal to the right argument.
 
2971
    1           left argument is greater than the right argument.
 
2972
*/
 
2973
static inline int cmp_longs (longlong a_val, longlong b_val)
 
2974
{
 
2975
  return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
 
2976
}
 
2977
 
 
2978
 
 
2979
/*
 
2980
  Determine which of the unsigned longlong arguments is bigger
 
2981
 
 
2982
  SYNOPSIS
 
2983
    cmp_ulongs()
 
2984
      a_val     left argument
 
2985
      b_val     right argument
 
2986
 
 
2987
  DESCRIPTION
 
2988
    This function will compare two unsigned longlong arguments
 
2989
    and will return -1, 0, or 1 if left argument is smaller than,
 
2990
    equal to or greater than the right argument.
 
2991
 
 
2992
  RETURN VALUE
 
2993
    -1          left argument is smaller than the right argument.
 
2994
    0           left argument is equal to the right argument.
 
2995
    1           left argument is greater than the right argument.
 
2996
*/
 
2997
static inline int cmp_ulongs (ulonglong a_val, ulonglong b_val)
 
2998
{
 
2999
  return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
 
3000
}
 
3001
 
 
3002
 
 
3003
/*
 
3004
  Compare two integers in IN value list format (packed_longlong) 
 
3005
 
 
3006
  SYNOPSIS
 
3007
    cmp_longlong()
 
3008
      cmp_arg   an argument passed to the calling function (my_qsort2)
 
3009
      a         left argument
 
3010
      b         right argument
 
3011
 
 
3012
  DESCRIPTION
 
3013
    This function will compare two integer arguments in the IN value list
 
3014
    format and will return -1, 0, or 1 if left argument is smaller than,
 
3015
    equal to or greater than the right argument.
 
3016
    It's used in sorting the IN values list and finding an element in it.
 
3017
    Depending on the signedness of the arguments cmp_longlong() will
 
3018
    compare them as either signed (using cmp_longs()) or unsigned (using
 
3019
    cmp_ulongs()).
 
3020
 
 
3021
  RETURN VALUE
 
3022
    -1          left argument is smaller than the right argument.
 
3023
    0           left argument is equal to the right argument.
 
3024
    1           left argument is greater than the right argument.
 
3025
*/
 
3026
int cmp_longlong(void *cmp_arg, 
 
3027
                 in_longlong::packed_longlong *a,
 
3028
                 in_longlong::packed_longlong *b)
 
3029
{
 
3030
  if (a->unsigned_flag != b->unsigned_flag)
 
3031
  { 
 
3032
    /* 
 
3033
      One of the args is unsigned and is too big to fit into the 
 
3034
      positive signed range. Report no match.
 
3035
    */  
 
3036
    if ((a->unsigned_flag && ((ulonglong) a->val) > (ulonglong) LONGLONG_MAX) ||
 
3037
        (b->unsigned_flag && ((ulonglong) b->val) > (ulonglong) LONGLONG_MAX))
 
3038
      return a->unsigned_flag ? 1 : -1;
 
3039
    /*
 
3040
      Although the signedness differs both args can fit into the signed 
 
3041
      positive range. Make them signed and compare as usual.
 
3042
    */  
 
3043
    return cmp_longs (a->val, b->val);
 
3044
  }
 
3045
  if (a->unsigned_flag)
 
3046
    return cmp_ulongs ((ulonglong) a->val, (ulonglong) b->val);
 
3047
  else
 
3048
    return cmp_longs (a->val, b->val);
 
3049
}
 
3050
 
 
3051
static int cmp_double(void *cmp_arg, double *a,double *b)
 
3052
{
 
3053
  return *a < *b ? -1 : *a == *b ? 0 : 1;
 
3054
}
 
3055
 
 
3056
static int cmp_row(void *cmp_arg, cmp_item_row *a, cmp_item_row *b)
 
3057
{
 
3058
  return a->compare(b);
 
3059
}
 
3060
 
 
3061
 
 
3062
static int cmp_decimal(void *cmp_arg, my_decimal *a, my_decimal *b)
 
3063
{
 
3064
  /*
 
3065
    We need call of fixing buffer pointer, because fast sort just copy
 
3066
    decimal buffers in memory and pointers left pointing on old buffer place
 
3067
  */
 
3068
  a->fix_buffer_pointer();
 
3069
  b->fix_buffer_pointer();
 
3070
  return my_decimal_cmp(a, b);
 
3071
}
 
3072
 
 
3073
 
 
3074
int in_vector::find(Item *item)
 
3075
{
 
3076
  uchar *result=get_value(item);
 
3077
  if (!result || !used_count)
 
3078
    return 0;                           // Null value
 
3079
 
 
3080
  uint start,end;
 
3081
  start=0; end=used_count-1;
 
3082
  while (start != end)
 
3083
  {
 
3084
    uint mid=(start+end+1)/2;
 
3085
    int res;
 
3086
    if ((res=(*compare)(collation, base+mid*size, result)) == 0)
 
3087
      return 1;
 
3088
    if (res < 0)
 
3089
      start=mid;
 
3090
    else
 
3091
      end=mid-1;
 
3092
  }
 
3093
  return (int) ((*compare)(collation, base+start*size, result) == 0);
 
3094
}
 
3095
 
 
3096
in_string::in_string(uint elements,qsort2_cmp cmp_func, CHARSET_INFO *cs)
 
3097
  :in_vector(elements, sizeof(String), cmp_func, cs),
 
3098
   tmp(buff, sizeof(buff), &my_charset_bin)
 
3099
{}
 
3100
 
 
3101
in_string::~in_string()
 
3102
{
 
3103
  if (base)
 
3104
  {
 
3105
    // base was allocated with help of sql_alloc => following is OK
 
3106
    for (uint i=0 ; i < count ; i++)
 
3107
      ((String*) base)[i].free();
 
3108
  }
 
3109
}
 
3110
 
 
3111
void in_string::set(uint pos,Item *item)
 
3112
{
 
3113
  String *str=((String*) base)+pos;
 
3114
  String *res=item->val_str(str);
 
3115
  if (res && res != str)
 
3116
  {
 
3117
    if (res->uses_buffer_owned_by(str))
 
3118
      res->copy();
 
3119
    if (item->type() == Item::FUNC_ITEM)
 
3120
      str->copy(*res);
 
3121
    else
 
3122
      *str= *res;
 
3123
  }
 
3124
  if (!str->charset())
 
3125
  {
 
3126
    CHARSET_INFO *cs;
 
3127
    if (!(cs= item->collation.collation))
 
3128
      cs= &my_charset_bin;              // Should never happen for STR items
 
3129
    str->set_charset(cs);
 
3130
  }
 
3131
}
 
3132
 
 
3133
 
 
3134
uchar *in_string::get_value(Item *item)
 
3135
{
 
3136
  return (uchar*) item->val_str(&tmp);
 
3137
}
 
3138
 
 
3139
in_row::in_row(uint elements, Item * item)
 
3140
{
 
3141
  base= (char*) new cmp_item_row[count= elements];
 
3142
  size= sizeof(cmp_item_row);
 
3143
  compare= (qsort2_cmp) cmp_row;
 
3144
  /*
 
3145
    We need to reset these as otherwise we will call sort() with
 
3146
    uninitialized (even if not used) elements
 
3147
  */
 
3148
  used_count= elements;
 
3149
  collation= 0;
 
3150
}
 
3151
 
 
3152
in_row::~in_row()
 
3153
{
 
3154
  if (base)
 
3155
    delete [] (cmp_item_row*) base;
 
3156
}
 
3157
 
 
3158
uchar *in_row::get_value(Item *item)
 
3159
{
 
3160
  tmp.store_value(item);
 
3161
  if (item->is_null())
 
3162
    return 0;
 
3163
  return (uchar *)&tmp;
 
3164
}
 
3165
 
 
3166
void in_row::set(uint pos, Item *item)
 
3167
{
 
3168
  DBUG_ENTER("in_row::set");
 
3169
  DBUG_PRINT("enter", ("pos: %u  item: 0x%lx", pos, (ulong) item));
 
3170
  ((cmp_item_row*) base)[pos].store_value_by_template(&tmp, item);
 
3171
  DBUG_VOID_RETURN;
 
3172
}
 
3173
 
 
3174
in_longlong::in_longlong(uint elements)
 
3175
  :in_vector(elements,sizeof(packed_longlong),(qsort2_cmp) cmp_longlong, 0)
 
3176
{}
 
3177
 
 
3178
void in_longlong::set(uint pos,Item *item)
 
3179
{
 
3180
  struct packed_longlong *buff= &((packed_longlong*) base)[pos];
 
3181
  
 
3182
  buff->val= item->val_int();
 
3183
  buff->unsigned_flag= item->unsigned_flag;
 
3184
}
 
3185
 
 
3186
uchar *in_longlong::get_value(Item *item)
 
3187
{
 
3188
  tmp.val= item->val_int();
 
3189
  if (item->null_value)
 
3190
    return 0;
 
3191
  tmp.unsigned_flag= item->unsigned_flag;
 
3192
  return (uchar*) &tmp;
 
3193
}
 
3194
 
 
3195
void in_datetime::set(uint pos,Item *item)
 
3196
{
 
3197
  Item **tmp_item= &item;
 
3198
  bool is_null;
 
3199
  struct packed_longlong *buff= &((packed_longlong*) base)[pos];
 
3200
 
 
3201
  buff->val= get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null);
 
3202
  buff->unsigned_flag= 1L;
 
3203
}
 
3204
 
 
3205
uchar *in_datetime::get_value(Item *item)
 
3206
{
 
3207
  bool is_null;
 
3208
  Item **tmp_item= lval_cache ? &lval_cache : &item;
 
3209
  tmp.val= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null);
 
3210
  if (item->null_value)
 
3211
    return 0;
 
3212
  tmp.unsigned_flag= 1L;
 
3213
  return (uchar*) &tmp;
 
3214
}
 
3215
 
 
3216
in_double::in_double(uint elements)
 
3217
  :in_vector(elements,sizeof(double),(qsort2_cmp) cmp_double, 0)
 
3218
{}
 
3219
 
 
3220
void in_double::set(uint pos,Item *item)
 
3221
{
 
3222
  ((double*) base)[pos]= item->val_real();
 
3223
}
 
3224
 
 
3225
uchar *in_double::get_value(Item *item)
 
3226
{
 
3227
  tmp= item->val_real();
 
3228
  if (item->null_value)
 
3229
    return 0;                                   /* purecov: inspected */
 
3230
  return (uchar*) &tmp;
 
3231
}
 
3232
 
 
3233
 
 
3234
in_decimal::in_decimal(uint elements)
 
3235
  :in_vector(elements, sizeof(my_decimal),(qsort2_cmp) cmp_decimal, 0)
 
3236
{}
 
3237
 
 
3238
 
 
3239
void in_decimal::set(uint pos, Item *item)
 
3240
{
 
3241
  /* as far as 'item' is constant, we can store reference on my_decimal */
 
3242
  my_decimal *dec= ((my_decimal *)base) + pos;
 
3243
  dec->len= DECIMAL_BUFF_LENGTH;
 
3244
  dec->fix_buffer_pointer();
 
3245
  my_decimal *res= item->val_decimal(dec);
 
3246
  /* if item->val_decimal() is evaluated to NULL then res == 0 */ 
 
3247
  if (!item->null_value && res != dec)
 
3248
    my_decimal2decimal(res, dec);
 
3249
}
 
3250
 
 
3251
 
 
3252
uchar *in_decimal::get_value(Item *item)
 
3253
{
 
3254
  my_decimal *result= item->val_decimal(&val);
 
3255
  if (item->null_value)
 
3256
    return 0;
 
3257
  return (uchar *)result;
 
3258
}
 
3259
 
 
3260
 
 
3261
cmp_item* cmp_item::get_comparator(Item_result type,
 
3262
                                   CHARSET_INFO *cs)
 
3263
{
 
3264
  switch (type) {
 
3265
  case STRING_RESULT:
 
3266
    return new cmp_item_sort_string(cs);
 
3267
  case INT_RESULT:
 
3268
    return new cmp_item_int;
 
3269
  case REAL_RESULT:
 
3270
    return new cmp_item_real;
 
3271
  case ROW_RESULT:
 
3272
    return new cmp_item_row;
 
3273
  case DECIMAL_RESULT:
 
3274
    return new cmp_item_decimal;
 
3275
  default:
 
3276
    DBUG_ASSERT(0);
 
3277
    break;
 
3278
  }
 
3279
  return 0; // to satisfy compiler :)
 
3280
}
 
3281
 
 
3282
 
 
3283
cmp_item* cmp_item_sort_string::make_same()
 
3284
{
 
3285
  return new cmp_item_sort_string_in_static(cmp_charset);
 
3286
}
 
3287
 
 
3288
cmp_item* cmp_item_int::make_same()
 
3289
{
 
3290
  return new cmp_item_int();
 
3291
}
 
3292
 
 
3293
cmp_item* cmp_item_real::make_same()
 
3294
{
 
3295
  return new cmp_item_real();
 
3296
}
 
3297
 
 
3298
cmp_item* cmp_item_row::make_same()
 
3299
{
 
3300
  return new cmp_item_row();
 
3301
}
 
3302
 
 
3303
 
 
3304
cmp_item_row::~cmp_item_row()
 
3305
{
 
3306
  DBUG_ENTER("~cmp_item_row");
 
3307
  DBUG_PRINT("enter",("this: 0x%lx", (long) this));
 
3308
  if (comparators)
 
3309
  {
 
3310
    for (uint i= 0; i < n; i++)
 
3311
    {
 
3312
      if (comparators[i])
 
3313
        delete comparators[i];
 
3314
    }
 
3315
  }
 
3316
  DBUG_VOID_RETURN;
 
3317
}
 
3318
 
 
3319
 
 
3320
void cmp_item_row::alloc_comparators()
 
3321
{
 
3322
  if (!comparators)
 
3323
    comparators= (cmp_item **) current_thd->calloc(sizeof(cmp_item *)*n);
 
3324
}
 
3325
 
 
3326
 
 
3327
void cmp_item_row::store_value(Item *item)
 
3328
{
 
3329
  DBUG_ENTER("cmp_item_row::store_value");
 
3330
  n= item->cols();
 
3331
  alloc_comparators();
 
3332
  if (comparators)
 
3333
  {
 
3334
    item->bring_value();
 
3335
    item->null_value= 0;
 
3336
    for (uint i=0; i < n; i++)
 
3337
    {
 
3338
      if (!comparators[i])
 
3339
        if (!(comparators[i]=
 
3340
              cmp_item::get_comparator(item->element_index(i)->result_type(),
 
3341
                                       item->element_index(i)->collation.collation)))
 
3342
          break;                                        // new failed
 
3343
      comparators[i]->store_value(item->element_index(i));
 
3344
      item->null_value|= item->element_index(i)->null_value;
 
3345
    }
 
3346
  }
 
3347
  DBUG_VOID_RETURN;
 
3348
}
 
3349
 
 
3350
 
 
3351
void cmp_item_row::store_value_by_template(cmp_item *t, Item *item)
 
3352
{
 
3353
  cmp_item_row *tmpl= (cmp_item_row*) t;
 
3354
  if (tmpl->n != item->cols())
 
3355
  {
 
3356
    my_error(ER_OPERAND_COLUMNS, MYF(0), tmpl->n);
 
3357
    return;
 
3358
  }
 
3359
  n= tmpl->n;
 
3360
  if ((comparators= (cmp_item **) sql_alloc(sizeof(cmp_item *)*n)))
 
3361
  {
 
3362
    item->bring_value();
 
3363
    item->null_value= 0;
 
3364
    for (uint i=0; i < n; i++)
 
3365
    {
 
3366
      if (!(comparators[i]= tmpl->comparators[i]->make_same()))
 
3367
        break;                                  // new failed
 
3368
      comparators[i]->store_value_by_template(tmpl->comparators[i],
 
3369
                                              item->element_index(i));
 
3370
      item->null_value|= item->element_index(i)->null_value;
 
3371
    }
 
3372
  }
 
3373
}
 
3374
 
 
3375
 
 
3376
int cmp_item_row::cmp(Item *arg)
 
3377
{
 
3378
  arg->null_value= 0;
 
3379
  if (arg->cols() != n)
 
3380
  {
 
3381
    my_error(ER_OPERAND_COLUMNS, MYF(0), n);
 
3382
    return 1;
 
3383
  }
 
3384
  bool was_null= 0;
 
3385
  arg->bring_value();
 
3386
  for (uint i=0; i < n; i++)
 
3387
  {
 
3388
    if (comparators[i]->cmp(arg->element_index(i)))
 
3389
    {
 
3390
      if (!arg->element_index(i)->null_value)
 
3391
        return 1;
 
3392
      was_null= 1;
 
3393
    }
 
3394
  }
 
3395
  return (arg->null_value= was_null);
 
3396
}
 
3397
 
 
3398
 
 
3399
int cmp_item_row::compare(cmp_item *c)
 
3400
{
 
3401
  cmp_item_row *l_cmp= (cmp_item_row *) c;
 
3402
  for (uint i=0; i < n; i++)
 
3403
  {
 
3404
    int res;
 
3405
    if ((res= comparators[i]->compare(l_cmp->comparators[i])))
 
3406
      return res;
 
3407
  }
 
3408
  return 0;
 
3409
}
 
3410
 
 
3411
 
 
3412
void cmp_item_decimal::store_value(Item *item)
 
3413
{
 
3414
  my_decimal *val= item->val_decimal(&value);
 
3415
  /* val may be zero if item is nnull */
 
3416
  if (val && val != &value)
 
3417
    my_decimal2decimal(val, &value);
 
3418
}
 
3419
 
 
3420
 
 
3421
int cmp_item_decimal::cmp(Item *arg)
 
3422
{
 
3423
  my_decimal tmp_buf, *tmp= arg->val_decimal(&tmp_buf);
 
3424
  if (arg->null_value)
 
3425
    return 1;
 
3426
  return my_decimal_cmp(&value, tmp);
 
3427
}
 
3428
 
 
3429
 
 
3430
int cmp_item_decimal::compare(cmp_item *arg)
 
3431
{
 
3432
  cmp_item_decimal *l_cmp= (cmp_item_decimal*) arg;
 
3433
  return my_decimal_cmp(&value, &l_cmp->value);
 
3434
}
 
3435
 
 
3436
 
 
3437
cmp_item* cmp_item_decimal::make_same()
 
3438
{
 
3439
  return new cmp_item_decimal();
 
3440
}
 
3441
 
 
3442
 
 
3443
void cmp_item_datetime::store_value(Item *item)
 
3444
{
 
3445
  bool is_null;
 
3446
  Item **tmp_item= lval_cache ? &lval_cache : &item;
 
3447
  value= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null);
 
3448
}
 
3449
 
 
3450
 
 
3451
int cmp_item_datetime::cmp(Item *arg)
 
3452
{
 
3453
  bool is_null;
 
3454
  Item **tmp_item= &arg;
 
3455
  return value !=
 
3456
    get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null);
 
3457
}
 
3458
 
 
3459
 
 
3460
int cmp_item_datetime::compare(cmp_item *ci)
 
3461
{
 
3462
  cmp_item_datetime *l_cmp= (cmp_item_datetime *)ci;
 
3463
  return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1);
 
3464
}
 
3465
 
 
3466
 
 
3467
cmp_item *cmp_item_datetime::make_same()
 
3468
{
 
3469
  return new cmp_item_datetime(warn_item);
 
3470
}
 
3471
 
 
3472
 
 
3473
bool Item_func_in::nulls_in_row()
 
3474
{
 
3475
  Item **arg,**arg_end;
 
3476
  for (arg= args+1, arg_end= args+arg_count; arg != arg_end ; arg++)
 
3477
  {
 
3478
    if ((*arg)->null_inside())
 
3479
      return 1;
 
3480
  }
 
3481
  return 0;
 
3482
}
 
3483
 
 
3484
 
 
3485
/**
 
3486
  Perform context analysis of an IN item tree.
 
3487
 
 
3488
    This function performs context analysis (name resolution) and calculates
 
3489
    various attributes of the item tree with Item_func_in as its root.
 
3490
    The function saves in ref the pointer to the item or to a newly created
 
3491
    item that is considered as a replacement for the original one.
 
3492
 
 
3493
  @param thd     reference to the global context of the query thread
 
3494
  @param ref     pointer to Item* variable where pointer to resulting "fixed"
 
3495
                 item is to be assigned
 
3496
 
 
3497
  @note
 
3498
    Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
 
3499
    a predicate/function level. Then it's easy to show that:
 
3500
    @verbatim
 
3501
      T0(e IN(e1,...,en))     = union(T1(e),intersection(T1(ei)))
 
3502
      T1(e IN(e1,...,en))     = union(T1(e),intersection(T1(ei)))
 
3503
      T0(e NOT IN(e1,...,en)) = union(T1(e),union(T1(ei)))
 
3504
      T1(e NOT IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
 
3505
    @endverbatim
 
3506
 
 
3507
  @retval
 
3508
    0   ok
 
3509
  @retval
 
3510
    1   got error
 
3511
*/
 
3512
 
 
3513
bool
 
3514
Item_func_in::fix_fields(THD *thd, Item **ref)
 
3515
{
 
3516
  Item **arg, **arg_end;
 
3517
 
 
3518
  if (Item_func_opt_neg::fix_fields(thd, ref))
 
3519
    return 1;
 
3520
 
 
3521
  /* not_null_tables_cache == union(T1(e),union(T1(ei))) */
 
3522
  if (pred_level && negated)
 
3523
    return 0;
 
3524
 
 
3525
  /* not_null_tables_cache = union(T1(e),intersection(T1(ei))) */
 
3526
  not_null_tables_cache= ~(table_map) 0;
 
3527
  for (arg= args + 1, arg_end= args + arg_count; arg != arg_end; arg++)
 
3528
    not_null_tables_cache&= (*arg)->not_null_tables();
 
3529
  not_null_tables_cache|= (*args)->not_null_tables();
 
3530
  return 0;
 
3531
}
 
3532
 
 
3533
 
 
3534
static int srtcmp_in(CHARSET_INFO *cs, const String *x,const String *y)
 
3535
{
 
3536
  return cs->coll->strnncollsp(cs,
 
3537
                               (uchar *) x->ptr(),x->length(),
 
3538
                               (uchar *) y->ptr(),y->length(), 0);
 
3539
}
 
3540
 
 
3541
 
 
3542
void Item_func_in::fix_length_and_dec()
 
3543
{
 
3544
  Item **arg, **arg_end;
 
3545
  bool const_itm= 1;
 
3546
  THD *thd= current_thd;
 
3547
  bool datetime_found= FALSE;
 
3548
  /* TRUE <=> arguments values will be compared as DATETIMEs. */
 
3549
  bool compare_as_datetime= FALSE;
 
3550
  Item *date_arg= 0;
 
3551
  uint found_types= 0;
 
3552
  uint type_cnt= 0, i;
 
3553
  Item_result cmp_type= STRING_RESULT;
 
3554
  left_result_type= args[0]->result_type();
 
3555
  if (!(found_types= collect_cmp_types(args, arg_count)))
 
3556
    return;
 
3557
  
 
3558
  for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
 
3559
  {
 
3560
    if (!arg[0]->const_item())
 
3561
    {
 
3562
      const_itm= 0;
 
3563
      break;
 
3564
    }
 
3565
  }
 
3566
  for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
 
3567
  {
 
3568
    if (found_types & 1 << i)
 
3569
    {
 
3570
      (type_cnt)++;
 
3571
      cmp_type= (Item_result) i;
 
3572
    }
 
3573
  }
 
3574
 
 
3575
  if (type_cnt == 1)
 
3576
  {
 
3577
    if (cmp_type == STRING_RESULT && 
 
3578
        agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1))
 
3579
      return;
 
3580
    arg_types_compatible= TRUE;
 
3581
  }
 
3582
  if (type_cnt == 1)
 
3583
  {
 
3584
    /*
 
3585
      When comparing rows create the row comparator object beforehand to ease
 
3586
      the DATETIME comparison detection procedure.
 
3587
    */
 
3588
    if (cmp_type == ROW_RESULT)
 
3589
    {
 
3590
      cmp_item_row *cmp= 0;
 
3591
      if (const_itm && !nulls_in_row())
 
3592
      {
 
3593
        array= new in_row(arg_count-1, 0);
 
3594
        cmp= &((in_row*)array)->tmp;
 
3595
      }
 
3596
      else
 
3597
      {
 
3598
        if (!(cmp= new cmp_item_row))
 
3599
          return;
 
3600
        cmp_items[ROW_RESULT]= cmp;
 
3601
      }
 
3602
      cmp->n= args[0]->cols();
 
3603
      cmp->alloc_comparators();
 
3604
    }
 
3605
    /* All DATE/DATETIME fields/functions has the STRING result type. */
 
3606
    if (cmp_type == STRING_RESULT || cmp_type == ROW_RESULT)
 
3607
    {
 
3608
      uint col, cols= args[0]->cols();
 
3609
 
 
3610
      for (col= 0; col < cols; col++)
 
3611
      {
 
3612
        bool skip_column= FALSE;
 
3613
        /*
 
3614
          Check that all items to be compared has the STRING result type and at
 
3615
          least one of them is a DATE/DATETIME item.
 
3616
        */
 
3617
        for (arg= args, arg_end= args + arg_count; arg != arg_end ; arg++)
 
3618
        {
 
3619
          Item *itm= ((cmp_type == STRING_RESULT) ? arg[0] :
 
3620
                      arg[0]->element_index(col));
 
3621
          if (itm->result_type() != STRING_RESULT)
 
3622
          {
 
3623
            skip_column= TRUE;
 
3624
            break;
 
3625
          }
 
3626
          else if (itm->is_datetime())
 
3627
          {
 
3628
            datetime_found= TRUE;
 
3629
            /*
 
3630
              Internally all DATE/DATETIME values are converted to the DATETIME
 
3631
              type. So try to find a DATETIME item to issue correct warnings.
 
3632
            */
 
3633
            if (!date_arg)
 
3634
              date_arg= itm;
 
3635
            else if (itm->field_type() == MYSQL_TYPE_DATETIME)
 
3636
            {
 
3637
              date_arg= itm;
 
3638
              /* All arguments are already checked to have the STRING result. */
 
3639
              if (cmp_type == STRING_RESULT)
 
3640
                break;
 
3641
            }
 
3642
          }
 
3643
        }
 
3644
        if (skip_column)
 
3645
          continue;
 
3646
        if (datetime_found)
 
3647
        {
 
3648
          if (cmp_type == ROW_RESULT)
 
3649
          {
 
3650
            cmp_item **cmp= 0;
 
3651
            if (array)
 
3652
              cmp= ((in_row*)array)->tmp.comparators + col;
 
3653
            else
 
3654
              cmp= ((cmp_item_row*)cmp_items[ROW_RESULT])->comparators + col;
 
3655
            *cmp= new cmp_item_datetime(date_arg);
 
3656
            /* Reset variables for the next column. */
 
3657
            date_arg= 0;
 
3658
            datetime_found= FALSE;
 
3659
          }
 
3660
          else
 
3661
            compare_as_datetime= TRUE;
 
3662
        }
 
3663
      }
 
3664
    }
 
3665
  }
 
3666
  /*
 
3667
    Row item with NULLs inside can return NULL or FALSE =>
 
3668
    they can't be processed as static
 
3669
  */
 
3670
  if (type_cnt == 1 && const_itm && !nulls_in_row())
 
3671
  {
 
3672
    if (compare_as_datetime)
 
3673
      array= new in_datetime(date_arg, arg_count - 1);
 
3674
    else
 
3675
    {
 
3676
      /*
 
3677
        IN must compare INT columns and constants as int values (the same
 
3678
        way as equality does).
 
3679
        So we must check here if the column on the left and all the constant 
 
3680
        values on the right can be compared as integers and adjust the 
 
3681
        comparison type accordingly.
 
3682
      */  
 
3683
      if (args[0]->real_item()->type() == FIELD_ITEM &&
 
3684
          thd->lex->sql_command != SQLCOM_SHOW_CREATE &&
 
3685
          cmp_type != INT_RESULT)
 
3686
      {
 
3687
        Item_field *field_item= (Item_field*) (args[0]->real_item());
 
3688
        if (field_item->field->can_be_compared_as_longlong())
 
3689
        {
 
3690
          bool all_converted= TRUE;
 
3691
          for (arg=args+1, arg_end=args+arg_count; arg != arg_end ; arg++)
 
3692
          {
 
3693
            if (!convert_constant_item (thd, field_item, &arg[0]))
 
3694
              all_converted= FALSE;
 
3695
          }
 
3696
          if (all_converted)
 
3697
            cmp_type= INT_RESULT;
 
3698
        }
 
3699
      }
 
3700
      switch (cmp_type) {
 
3701
      case STRING_RESULT:
 
3702
        array=new in_string(arg_count-1,(qsort2_cmp) srtcmp_in, 
 
3703
                            cmp_collation.collation);
 
3704
        break;
 
3705
      case INT_RESULT:
 
3706
        array= new in_longlong(arg_count-1);
 
3707
        break;
 
3708
      case REAL_RESULT:
 
3709
        array= new in_double(arg_count-1);
 
3710
        break;
 
3711
      case ROW_RESULT:
 
3712
        /*
 
3713
          The row comparator was created at the beginning but only DATETIME
 
3714
          items comparators were initialized. Call store_value() to setup
 
3715
          others.
 
3716
        */
 
3717
        ((in_row*)array)->tmp.store_value(args[0]);
 
3718
        break;
 
3719
      case DECIMAL_RESULT:
 
3720
        array= new in_decimal(arg_count - 1);
 
3721
        break;
 
3722
      default:
 
3723
        DBUG_ASSERT(0);
 
3724
        return;
 
3725
      }
 
3726
    }
 
3727
    if (array && !(thd->is_fatal_error))                // If not EOM
 
3728
    {
 
3729
      uint j=0;
 
3730
      for (uint i=1 ; i < arg_count ; i++)
 
3731
      {
 
3732
        array->set(j,args[i]);
 
3733
        if (!args[i]->null_value)                       // Skip NULL values
 
3734
          j++;
 
3735
        else
 
3736
          have_null= 1;
 
3737
      }
 
3738
      if ((array->used_count= j))
 
3739
        array->sort();
 
3740
    }
 
3741
  }
 
3742
  else
 
3743
  {
 
3744
    if (compare_as_datetime)
 
3745
      cmp_items[STRING_RESULT]= new cmp_item_datetime(date_arg);
 
3746
    else
 
3747
    {
 
3748
      for (i= 0; i <= (uint) DECIMAL_RESULT; i++)
 
3749
      {
 
3750
        if (found_types & (1 << i) && !cmp_items[i])
 
3751
        {
 
3752
          if ((Item_result)i == STRING_RESULT &&
 
3753
              agg_arg_charsets(cmp_collation, args, arg_count,
 
3754
                               MY_COLL_CMP_CONV, 1))
 
3755
            return;
 
3756
          if (!cmp_items[i] && !(cmp_items[i]=
 
3757
              cmp_item::get_comparator((Item_result)i,
 
3758
                                       cmp_collation.collation)))
 
3759
            return;
 
3760
        }
 
3761
      }
 
3762
    }
 
3763
  }
 
3764
  max_length= 1;
 
3765
}
 
3766
 
 
3767
 
 
3768
void Item_func_in::print(String *str, enum_query_type query_type)
 
3769
{
 
3770
  str->append('(');
 
3771
  args[0]->print(str, query_type);
 
3772
  if (negated)
 
3773
    str->append(STRING_WITH_LEN(" not"));
 
3774
  str->append(STRING_WITH_LEN(" in ("));
 
3775
  print_args(str, 1, query_type);
 
3776
  str->append(STRING_WITH_LEN("))"));
 
3777
}
 
3778
 
 
3779
 
 
3780
/*
 
3781
  Evaluate the function and return its value.
 
3782
 
 
3783
  SYNOPSIS
 
3784
    val_int()
 
3785
 
 
3786
  DESCRIPTION
 
3787
    Evaluate the function and return its value.
 
3788
 
 
3789
  IMPLEMENTATION
 
3790
    If the array object is defined then the value of the function is
 
3791
    calculated by means of this array.
 
3792
    Otherwise several cmp_item objects are used in order to do correct
 
3793
    comparison of left expression and an expression from the values list.
 
3794
    One cmp_item object correspond to one used comparison type. Left
 
3795
    expression can be evaluated up to number of different used comparison
 
3796
    types. A bit mapped variable value_added_map is used to check whether
 
3797
    the left expression already was evaluated for a particular result type.
 
3798
    Result types are mapped to it according to their integer values i.e.
 
3799
    STRING_RESULT is mapped to bit 0, REAL_RESULT to bit 1, so on.
 
3800
 
 
3801
  RETURN
 
3802
    Value of the function
 
3803
*/
 
3804
 
 
3805
longlong Item_func_in::val_int()
 
3806
{
 
3807
  cmp_item *in_item;
 
3808
  DBUG_ASSERT(fixed == 1);
 
3809
  uint value_added_map= 0;
 
3810
  if (array)
 
3811
  {
 
3812
    int tmp=array->find(args[0]);
 
3813
    null_value=args[0]->null_value || (!tmp && have_null);
 
3814
    return (longlong) (!null_value && tmp != negated);
 
3815
  }
 
3816
 
 
3817
  for (uint i= 1 ; i < arg_count ; i++)
 
3818
  {
 
3819
    Item_result cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
 
3820
    in_item= cmp_items[(uint)cmp_type];
 
3821
    DBUG_ASSERT(in_item);
 
3822
    if (!(value_added_map & (1 << (uint)cmp_type)))
 
3823
    {
 
3824
      in_item->store_value(args[0]);
 
3825
      if ((null_value=args[0]->null_value))
 
3826
        return 0;
 
3827
      have_null= 0;
 
3828
      value_added_map|= 1 << (uint)cmp_type;
 
3829
    }
 
3830
    if (!in_item->cmp(args[i]) && !args[i]->null_value)
 
3831
      return (longlong) (!negated);
 
3832
    have_null|= args[i]->null_value;
 
3833
  }
 
3834
 
 
3835
  null_value= have_null;
 
3836
  return (longlong) (!null_value && negated);
 
3837
}
 
3838
 
 
3839
 
 
3840
longlong Item_func_bit_or::val_int()
 
3841
{
 
3842
  DBUG_ASSERT(fixed == 1);
 
3843
  ulonglong arg1= (ulonglong) args[0]->val_int();
 
3844
  if (args[0]->null_value)
 
3845
  {
 
3846
    null_value=1; /* purecov: inspected */
 
3847
    return 0; /* purecov: inspected */
 
3848
  }
 
3849
  ulonglong arg2= (ulonglong) args[1]->val_int();
 
3850
  if (args[1]->null_value)
 
3851
  {
 
3852
    null_value=1;
 
3853
    return 0;
 
3854
  }
 
3855
  null_value=0;
 
3856
  return (longlong) (arg1 | arg2);
 
3857
}
 
3858
 
 
3859
 
 
3860
longlong Item_func_bit_and::val_int()
 
3861
{
 
3862
  DBUG_ASSERT(fixed == 1);
 
3863
  ulonglong arg1= (ulonglong) args[0]->val_int();
 
3864
  if (args[0]->null_value)
 
3865
  {
 
3866
    null_value=1; /* purecov: inspected */
 
3867
    return 0; /* purecov: inspected */
 
3868
  }
 
3869
  ulonglong arg2= (ulonglong) args[1]->val_int();
 
3870
  if (args[1]->null_value)
 
3871
  {
 
3872
    null_value=1; /* purecov: inspected */
 
3873
    return 0; /* purecov: inspected */
 
3874
  }
 
3875
  null_value=0;
 
3876
  return (longlong) (arg1 & arg2);
 
3877
}
 
3878
 
 
3879
Item_cond::Item_cond(THD *thd, Item_cond *item)
 
3880
  :Item_bool_func(thd, item),
 
3881
   abort_on_null(item->abort_on_null),
 
3882
   and_tables_cache(item->and_tables_cache)
 
3883
{
 
3884
  /*
 
3885
    item->list will be copied by copy_andor_arguments() call
 
3886
  */
 
3887
}
 
3888
 
 
3889
 
 
3890
void Item_cond::copy_andor_arguments(THD *thd, Item_cond *item)
 
3891
{
 
3892
  List_iterator_fast<Item> li(item->list);
 
3893
  while (Item *it= li++)
 
3894
    list.push_back(it->copy_andor_structure(thd));
 
3895
}
 
3896
 
 
3897
 
 
3898
bool
 
3899
Item_cond::fix_fields(THD *thd, Item **ref)
 
3900
{
 
3901
  DBUG_ASSERT(fixed == 0);
 
3902
  List_iterator<Item> li(list);
 
3903
  Item *item;
 
3904
  void *orig_thd_marker= thd->thd_marker;
 
3905
  uchar buff[sizeof(char*)];                    // Max local vars in function
 
3906
  not_null_tables_cache= used_tables_cache= 0;
 
3907
  const_item_cache= 1;
 
3908
 
 
3909
  if (functype() == COND_OR_FUNC)
 
3910
    thd->thd_marker= 0;
 
3911
  /*
 
3912
    and_table_cache is the value that Item_cond_or() returns for
 
3913
    not_null_tables()
 
3914
  */
 
3915
  and_tables_cache= ~(table_map) 0;
 
3916
 
 
3917
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
 
3918
    return TRUE;                                // Fatal error flag is set!
 
3919
  /*
 
3920
    The following optimization reduces the depth of an AND-OR tree.
 
3921
    E.g. a WHERE clause like
 
3922
      F1 AND (F2 AND (F2 AND F4))
 
3923
    is parsed into a tree with the same nested structure as defined
 
3924
    by braces. This optimization will transform such tree into
 
3925
      AND (F1, F2, F3, F4).
 
3926
    Trees of OR items are flattened as well:
 
3927
      ((F1 OR F2) OR (F3 OR F4))   =>   OR (F1, F2, F3, F4)
 
3928
    Items for removed AND/OR levels will dangle until the death of the
 
3929
    entire statement.
 
3930
    The optimization is currently prepared statements and stored procedures
 
3931
    friendly as it doesn't allocate any memory and its effects are durable
 
3932
    (i.e. do not depend on PS/SP arguments).
 
3933
  */
 
3934
  while ((item=li++))
 
3935
  {
 
3936
    table_map tmp_table_map;
 
3937
    while (item->type() == Item::COND_ITEM &&
 
3938
           ((Item_cond*) item)->functype() == functype() &&
 
3939
           !((Item_cond*) item)->list.is_empty())
 
3940
    {                                           // Identical function
 
3941
      li.replace(((Item_cond*) item)->list);
 
3942
      ((Item_cond*) item)->list.empty();
 
3943
      item= *li.ref();                          // new current item
 
3944
    }
 
3945
    if (abort_on_null)
 
3946
      item->top_level_item();
 
3947
 
 
3948
    // item can be substituted in fix_fields
 
3949
    if ((!item->fixed &&
 
3950
         item->fix_fields(thd, li.ref())) ||
 
3951
        (item= *li.ref())->check_cols(1))
 
3952
      return TRUE; /* purecov: inspected */
 
3953
    used_tables_cache|=     item->used_tables();
 
3954
    if (item->const_item())
 
3955
      and_tables_cache= (table_map) 0;
 
3956
    else
 
3957
    {
 
3958
      tmp_table_map= item->not_null_tables();
 
3959
      not_null_tables_cache|= tmp_table_map;
 
3960
      and_tables_cache&= tmp_table_map;
 
3961
      const_item_cache= FALSE;
 
3962
    }  
 
3963
    with_sum_func=          with_sum_func || item->with_sum_func;
 
3964
    with_subselect|=        item->with_subselect;
 
3965
    if (item->maybe_null)
 
3966
      maybe_null=1;
 
3967
  }
 
3968
  thd->lex->current_select->cond_count+= list.elements;
 
3969
  thd->thd_marker= orig_thd_marker;
 
3970
  fix_length_and_dec();
 
3971
  fixed= 1;
 
3972
  return FALSE;
 
3973
}
 
3974
 
 
3975
 
 
3976
void Item_cond::fix_after_pullout(st_select_lex *new_parent, Item **ref)
 
3977
{
 
3978
  List_iterator<Item> li(list);
 
3979
  Item *item;
 
3980
 
 
3981
  used_tables_cache=0;
 
3982
  const_item_cache=1;
 
3983
 
 
3984
  and_tables_cache= ~(table_map) 0; // Here and below we do as fix_fields does
 
3985
  not_null_tables_cache= 0;
 
3986
 
 
3987
  while ((item=li++))
 
3988
  {
 
3989
    table_map tmp_table_map;
 
3990
    item->fix_after_pullout(new_parent, li.ref());
 
3991
    item= *li.ref();
 
3992
    used_tables_cache|= item->used_tables();
 
3993
    const_item_cache&= item->const_item();
 
3994
 
 
3995
    if (item->const_item())
 
3996
      and_tables_cache= (table_map) 0;
 
3997
    else
 
3998
    {
 
3999
      tmp_table_map= item->not_null_tables();
 
4000
      not_null_tables_cache|= tmp_table_map;
 
4001
      and_tables_cache&= tmp_table_map;
 
4002
      const_item_cache= FALSE;
 
4003
    }  
 
4004
  }
 
4005
}
 
4006
 
 
4007
 
 
4008
bool Item_cond::walk(Item_processor processor, bool walk_subquery, uchar *arg)
 
4009
{
 
4010
  List_iterator_fast<Item> li(list);
 
4011
  Item *item;
 
4012
  while ((item= li++))
 
4013
    if (item->walk(processor, walk_subquery, arg))
 
4014
      return 1;
 
4015
  return Item_func::walk(processor, walk_subquery, arg);
 
4016
}
 
4017
 
 
4018
 
 
4019
/**
 
4020
  Transform an Item_cond object with a transformer callback function.
 
4021
  
 
4022
    The function recursively applies the transform method to each
 
4023
     member item of the condition list.
 
4024
    If the call of the method for a member item returns a new item
 
4025
    the old item is substituted for a new one.
 
4026
    After this the transformer is applied to the root node
 
4027
    of the Item_cond object. 
 
4028
     
 
4029
  @param transformer   the transformer callback function to be applied to
 
4030
                       the nodes of the tree of the object
 
4031
  @param arg           parameter to be passed to the transformer
 
4032
 
 
4033
  @return
 
4034
    Item returned as the result of transformation of the root node 
 
4035
*/
 
4036
 
 
4037
Item *Item_cond::transform(Item_transformer transformer, uchar *arg)
 
4038
{
 
4039
  List_iterator<Item> li(list);
 
4040
  Item *item;
 
4041
  while ((item= li++))
 
4042
  {
 
4043
    Item *new_item= item->transform(transformer, arg);
 
4044
    if (!new_item)
 
4045
      return 0;
 
4046
 
 
4047
    /*
 
4048
      THD::change_item_tree() should be called only if the tree was
 
4049
      really transformed, i.e. when a new item has been created.
 
4050
      Otherwise we'll be allocating a lot of unnecessary memory for
 
4051
      change records at each execution.
 
4052
    */
 
4053
    if (new_item != item)
 
4054
      current_thd->change_item_tree(li.ref(), new_item);
 
4055
  }
 
4056
  return Item_func::transform(transformer, arg);
 
4057
}
 
4058
 
 
4059
 
 
4060
/**
 
4061
  Compile Item_cond object with a processor and a transformer
 
4062
  callback functions.
 
4063
  
 
4064
    First the function applies the analyzer to the root node of
 
4065
    the Item_func object. Then if the analyzer succeeeds (returns TRUE)
 
4066
    the function recursively applies the compile method to member
 
4067
    item of the condition list.
 
4068
    If the call of the method for a member item returns a new item
 
4069
    the old item is substituted for a new one.
 
4070
    After this the transformer is applied to the root node
 
4071
    of the Item_cond object. 
 
4072
     
 
4073
  @param analyzer      the analyzer callback function to be applied to the
 
4074
                       nodes of the tree of the object
 
4075
  @param[in,out] arg_p parameter to be passed to the analyzer
 
4076
  @param transformer   the transformer callback function to be applied to the
 
4077
                       nodes of the tree of the object
 
4078
  @param arg_t         parameter to be passed to the transformer
 
4079
 
 
4080
  @return
 
4081
    Item returned as the result of transformation of the root node 
 
4082
*/
 
4083
 
 
4084
Item *Item_cond::compile(Item_analyzer analyzer, uchar **arg_p,
 
4085
                         Item_transformer transformer, uchar *arg_t)
 
4086
{
 
4087
  if (!(this->*analyzer)(arg_p))
 
4088
    return 0;
 
4089
  
 
4090
  List_iterator<Item> li(list);
 
4091
  Item *item;
 
4092
  while ((item= li++))
 
4093
  {
 
4094
    /* 
 
4095
      The same parameter value of arg_p must be passed
 
4096
      to analyze any argument of the condition formula.
 
4097
    */   
 
4098
    uchar *arg_v= *arg_p;
 
4099
    Item *new_item= item->compile(analyzer, &arg_v, transformer, arg_t);
 
4100
    if (new_item && new_item != item)
 
4101
      li.replace(new_item);
 
4102
  }
 
4103
  return Item_func::transform(transformer, arg_t);
 
4104
}
 
4105
 
 
4106
void Item_cond::traverse_cond(Cond_traverser traverser,
 
4107
                              void *arg, traverse_order order)
 
4108
{
 
4109
  List_iterator<Item> li(list);
 
4110
  Item *item;
 
4111
 
 
4112
  switch(order) {
 
4113
  case(PREFIX):
 
4114
    (*traverser)(this, arg);
 
4115
    while ((item= li++))
 
4116
    {
 
4117
      item->traverse_cond(traverser, arg, order);
 
4118
    }
 
4119
    (*traverser)(NULL, arg);
 
4120
    break;
 
4121
  case(POSTFIX):
 
4122
    while ((item= li++))
 
4123
    {
 
4124
      item->traverse_cond(traverser, arg, order);
 
4125
    }
 
4126
    (*traverser)(this, arg);
 
4127
  }
 
4128
}
 
4129
 
 
4130
/**
 
4131
  Move SUM items out from item tree and replace with reference.
 
4132
 
 
4133
  The split is done to get an unique item for each SUM function
 
4134
  so that we can easily find and calculate them.
 
4135
  (Calculation done by update_sum_func() and copy_sum_funcs() in
 
4136
  sql_select.cc)
 
4137
 
 
4138
  @param thd                    Thread handler
 
4139
  @param ref_pointer_array      Pointer to array of reference fields
 
4140
  @param fields         All fields in select
 
4141
 
 
4142
  @note
 
4143
    This function is run on all expression (SELECT list, WHERE, HAVING etc)
 
4144
    that have or refer (HAVING) to a SUM expression.
 
4145
*/
 
4146
 
 
4147
void Item_cond::split_sum_func(THD *thd, Item **ref_pointer_array,
 
4148
                               List<Item> &fields)
 
4149
{
 
4150
  List_iterator<Item> li(list);
 
4151
  Item *item;
 
4152
  while ((item= li++))
 
4153
    item->split_sum_func2(thd, ref_pointer_array, fields, li.ref(), TRUE);
 
4154
}
 
4155
 
 
4156
 
 
4157
table_map
 
4158
Item_cond::used_tables() const
 
4159
{                                               // This caches used_tables
 
4160
  return used_tables_cache;
 
4161
}
 
4162
 
 
4163
 
 
4164
void Item_cond::update_used_tables()
 
4165
{
 
4166
  List_iterator_fast<Item> li(list);
 
4167
  Item *item;
 
4168
 
 
4169
  used_tables_cache=0;
 
4170
  const_item_cache=1;
 
4171
  while ((item=li++))
 
4172
  {
 
4173
    item->update_used_tables();
 
4174
    used_tables_cache|= item->used_tables();
 
4175
    const_item_cache&= item->const_item();
 
4176
  }
 
4177
}
 
4178
 
 
4179
 
 
4180
void Item_cond::print(String *str, enum_query_type query_type)
 
4181
{
 
4182
  str->append('(');
 
4183
  List_iterator_fast<Item> li(list);
 
4184
  Item *item;
 
4185
  if ((item=li++))
 
4186
    item->print(str, query_type);
 
4187
  while ((item=li++))
 
4188
  {
 
4189
    str->append(' ');
 
4190
    str->append(func_name());
 
4191
    str->append(' ');
 
4192
    item->print(str, query_type);
 
4193
  }
 
4194
  str->append(')');
 
4195
}
 
4196
 
 
4197
 
 
4198
void Item_cond::neg_arguments(THD *thd)
 
4199
{
 
4200
  List_iterator<Item> li(list);
 
4201
  Item *item;
 
4202
  while ((item= li++))          /* Apply not transformation to the arguments */
 
4203
  {
 
4204
    Item *new_item= item->neg_transformer(thd);
 
4205
    if (!new_item)
 
4206
    {
 
4207
      if (!(new_item= new Item_func_not(item)))
 
4208
        return;                                 // Fatal OEM error
 
4209
    }
 
4210
    VOID(li.replace(new_item));
 
4211
  }
 
4212
}
 
4213
 
 
4214
 
 
4215
/**
 
4216
  Evaluation of AND(expr, expr, expr ...).
 
4217
 
 
4218
  @note
 
4219
    abort_if_null is set for AND expressions for which we don't care if the
 
4220
    result is NULL or 0. This is set for:
 
4221
    - WHERE clause
 
4222
    - HAVING clause
 
4223
    - IF(expression)
 
4224
 
 
4225
  @retval
 
4226
    1  If all expressions are true
 
4227
  @retval
 
4228
    0  If all expressions are false or if we find a NULL expression and
 
4229
       'abort_on_null' is set.
 
4230
  @retval
 
4231
    NULL if all expression are either 1 or NULL
 
4232
*/
 
4233
 
 
4234
 
 
4235
longlong Item_cond_and::val_int()
 
4236
{
 
4237
  DBUG_ASSERT(fixed == 1);
 
4238
  List_iterator_fast<Item> li(list);
 
4239
  Item *item;
 
4240
  null_value= 0;
 
4241
  while ((item=li++))
 
4242
  {
 
4243
    if (!item->val_bool())
 
4244
    {
 
4245
      if (abort_on_null || !(null_value= item->null_value))
 
4246
        return 0;                               // return FALSE
 
4247
    }
 
4248
  }
 
4249
  return null_value ? 0 : 1;
 
4250
}
 
4251
 
 
4252
 
 
4253
longlong Item_cond_or::val_int()
 
4254
{
 
4255
  DBUG_ASSERT(fixed == 1);
 
4256
  List_iterator_fast<Item> li(list);
 
4257
  Item *item;
 
4258
  null_value=0;
 
4259
  while ((item=li++))
 
4260
  {
 
4261
    if (item->val_bool())
 
4262
    {
 
4263
      null_value=0;
 
4264
      return 1;
 
4265
    }
 
4266
    if (item->null_value)
 
4267
      null_value=1;
 
4268
  }
 
4269
  return 0;
 
4270
}
 
4271
 
 
4272
/**
 
4273
  Create an AND expression from two expressions.
 
4274
 
 
4275
  @param a      expression or NULL
 
4276
  @param b      expression.
 
4277
  @param org_item       Don't modify a if a == *org_item.
 
4278
                        If a == NULL, org_item is set to point at b,
 
4279
                        to ensure that future calls will not modify b.
 
4280
 
 
4281
  @note
 
4282
    This will not modify item pointed to by org_item or b
 
4283
    The idea is that one can call this in a loop and create and
 
4284
    'and' over all items without modifying any of the original items.
 
4285
 
 
4286
  @retval
 
4287
    NULL        Error
 
4288
  @retval
 
4289
    Item
 
4290
*/
 
4291
 
 
4292
Item *and_expressions(Item *a, Item *b, Item **org_item)
 
4293
{
 
4294
  if (!a)
 
4295
    return (*org_item= (Item*) b);
 
4296
  if (a == *org_item)
 
4297
  {
 
4298
    Item_cond *res;
 
4299
    if ((res= new Item_cond_and(a, (Item*) b)))
 
4300
    {
 
4301
      res->used_tables_cache= a->used_tables() | b->used_tables();
 
4302
      res->not_null_tables_cache= a->not_null_tables() | b->not_null_tables();
 
4303
    }
 
4304
    return res;
 
4305
  }
 
4306
  if (((Item_cond_and*) a)->add((Item*) b))
 
4307
    return 0;
 
4308
  ((Item_cond_and*) a)->used_tables_cache|= b->used_tables();
 
4309
  ((Item_cond_and*) a)->not_null_tables_cache|= b->not_null_tables();
 
4310
  return a;
 
4311
}
 
4312
 
 
4313
 
 
4314
longlong Item_func_isnull::val_int()
 
4315
{
 
4316
  DBUG_ASSERT(fixed == 1);
 
4317
  /*
 
4318
    Handle optimization if the argument can't be null
 
4319
    This has to be here because of the test in update_used_tables().
 
4320
  */
 
4321
  if (!used_tables_cache && !with_subselect)
 
4322
    return cached_value;
 
4323
  return args[0]->is_null() ? 1: 0;
 
4324
}
 
4325
 
 
4326
longlong Item_is_not_null_test::val_int()
 
4327
{
 
4328
  DBUG_ASSERT(fixed == 1);
 
4329
  DBUG_ENTER("Item_is_not_null_test::val_int");
 
4330
  if (!used_tables_cache && !with_subselect)
 
4331
  {
 
4332
    owner->was_null|= (!cached_value);
 
4333
    DBUG_PRINT("info", ("cached: %ld", (long) cached_value));
 
4334
    DBUG_RETURN(cached_value);
 
4335
  }
 
4336
  if (args[0]->is_null())
 
4337
  {
 
4338
    DBUG_PRINT("info", ("null"));
 
4339
    owner->was_null|= 1;
 
4340
    DBUG_RETURN(0);
 
4341
  }
 
4342
  else
 
4343
    DBUG_RETURN(1);
 
4344
}
 
4345
 
 
4346
/**
 
4347
  Optimize case of not_null_column IS NULL.
 
4348
*/
 
4349
void Item_is_not_null_test::update_used_tables()
 
4350
{
 
4351
  if (!args[0]->maybe_null)
 
4352
  {
 
4353
    used_tables_cache= 0;                       /* is always true */
 
4354
    cached_value= (longlong) 1;
 
4355
  }
 
4356
  else
 
4357
  {
 
4358
    args[0]->update_used_tables();
 
4359
    if (!(used_tables_cache=args[0]->used_tables()) && !with_subselect)
 
4360
    {
 
4361
      /* Remember if the value is always NULL or never NULL */
 
4362
      cached_value= (longlong) !args[0]->is_null();
 
4363
    }
 
4364
  }
 
4365
}
 
4366
 
 
4367
 
 
4368
longlong Item_func_isnotnull::val_int()
 
4369
{
 
4370
  DBUG_ASSERT(fixed == 1);
 
4371
  return args[0]->is_null() ? 0 : 1;
 
4372
}
 
4373
 
 
4374
 
 
4375
void Item_func_isnotnull::print(String *str, enum_query_type query_type)
 
4376
{
 
4377
  str->append('(');
 
4378
  args[0]->print(str, query_type);
 
4379
  str->append(STRING_WITH_LEN(" is not null)"));
 
4380
}
 
4381
 
 
4382
 
 
4383
longlong Item_func_like::val_int()
 
4384
{
 
4385
  DBUG_ASSERT(fixed == 1);
 
4386
  String* res = args[0]->val_str(&tmp_value1);
 
4387
  if (args[0]->null_value)
 
4388
  {
 
4389
    null_value=1;
 
4390
    return 0;
 
4391
  }
 
4392
  String* res2 = args[1]->val_str(&tmp_value2);
 
4393
  if (args[1]->null_value)
 
4394
  {
 
4395
    null_value=1;
 
4396
    return 0;
 
4397
  }
 
4398
  null_value=0;
 
4399
  if (canDoTurboBM)
 
4400
    return turboBM_matches(res->ptr(), res->length()) ? 1 : 0;
 
4401
  return my_wildcmp(cmp.cmp_collation.collation,
 
4402
                    res->ptr(),res->ptr()+res->length(),
 
4403
                    res2->ptr(),res2->ptr()+res2->length(),
 
4404
                    escape,wild_one,wild_many) ? 0 : 1;
 
4405
}
 
4406
 
 
4407
 
 
4408
/**
 
4409
  We can optimize a where if first character isn't a wildcard
 
4410
*/
 
4411
 
 
4412
Item_func::optimize_type Item_func_like::select_optimize() const
 
4413
{
 
4414
  if (args[1]->const_item())
 
4415
  {
 
4416
    String* res2= args[1]->val_str((String *)&tmp_value2);
 
4417
 
 
4418
    if (!res2)
 
4419
      return OPTIMIZE_NONE;
 
4420
 
 
4421
    if (*res2->ptr() != wild_many)
 
4422
    {
 
4423
      if (args[0]->result_type() != STRING_RESULT || *res2->ptr() != wild_one)
 
4424
        return OPTIMIZE_OP;
 
4425
    }
 
4426
  }
 
4427
  return OPTIMIZE_NONE;
 
4428
}
 
4429
 
 
4430
 
 
4431
bool Item_func_like::fix_fields(THD *thd, Item **ref)
 
4432
{
 
4433
  DBUG_ASSERT(fixed == 0);
 
4434
  if (Item_bool_func2::fix_fields(thd, ref) ||
 
4435
      escape_item->fix_fields(thd, &escape_item))
 
4436
    return TRUE;
 
4437
 
 
4438
  if (!escape_item->const_during_execution())
 
4439
  {
 
4440
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
 
4441
    return TRUE;
 
4442
  }
 
4443
  
 
4444
  if (escape_item->const_item())
 
4445
  {
 
4446
    /* If we are on execution stage */
 
4447
    String *escape_str= escape_item->val_str(&tmp_value1);
 
4448
    if (escape_str)
 
4449
    {
 
4450
      if (escape_used_in_parsing && (
 
4451
             (((thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
 
4452
                escape_str->numchars() != 1) ||
 
4453
               escape_str->numchars() > 1)))
 
4454
      {
 
4455
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
 
4456
        return TRUE;
 
4457
      }
 
4458
 
 
4459
      if (use_mb(cmp.cmp_collation.collation))
 
4460
      {
 
4461
        CHARSET_INFO *cs= escape_str->charset();
 
4462
        my_wc_t wc;
 
4463
        int rc= cs->cset->mb_wc(cs, &wc,
 
4464
                                (const uchar*) escape_str->ptr(),
 
4465
                                (const uchar*) escape_str->ptr() +
 
4466
                                               escape_str->length());
 
4467
        escape= (int) (rc > 0 ? wc : '\\');
 
4468
      }
 
4469
      else
 
4470
      {
 
4471
        /*
 
4472
          In the case of 8bit character set, we pass native
 
4473
          code instead of Unicode code as "escape" argument.
 
4474
          Convert to "cs" if charset of escape differs.
 
4475
        */
 
4476
        CHARSET_INFO *cs= cmp.cmp_collation.collation;
 
4477
        uint32 unused;
 
4478
        if (escape_str->needs_conversion(escape_str->length(),
 
4479
                                         escape_str->charset(), cs, &unused))
 
4480
        {
 
4481
          char ch;
 
4482
          uint errors;
 
4483
          uint32 cnvlen= copy_and_convert(&ch, 1, cs, escape_str->ptr(),
 
4484
                                          escape_str->length(),
 
4485
                                          escape_str->charset(), &errors);
 
4486
          escape= cnvlen ? ch : '\\';
 
4487
        }
 
4488
        else
 
4489
          escape= *(escape_str->ptr());
 
4490
      }
 
4491
    }
 
4492
    else
 
4493
      escape= '\\';
 
4494
 
 
4495
    /*
 
4496
      We could also do boyer-more for non-const items, but as we would have to
 
4497
      recompute the tables for each row it's not worth it.
 
4498
    */
 
4499
    if (args[1]->const_item() && !use_strnxfrm(collation.collation) &&
 
4500
       !(specialflag & SPECIAL_NO_NEW_FUNC))
 
4501
    {
 
4502
      String* res2 = args[1]->val_str(&tmp_value2);
 
4503
      if (!res2)
 
4504
        return FALSE;                           // Null argument
 
4505
      
 
4506
      const size_t len   = res2->length();
 
4507
      const char*  first = res2->ptr();
 
4508
      const char*  last  = first + len - 1;
 
4509
      /*
 
4510
        len must be > 2 ('%pattern%')
 
4511
        heuristic: only do TurboBM for pattern_len > 2
 
4512
      */
 
4513
      
 
4514
      if (len > MIN_TURBOBM_PATTERN_LEN + 2 &&
 
4515
          *first == wild_many &&
 
4516
          *last  == wild_many)
 
4517
      {
 
4518
        const char* tmp = first + 1;
 
4519
        for (; *tmp != wild_many && *tmp != wild_one && *tmp != escape; tmp++) ;
 
4520
        canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation);
 
4521
      }
 
4522
      if (canDoTurboBM)
 
4523
      {
 
4524
        pattern     = first + 1;
 
4525
        pattern_len = (int) len - 2;
 
4526
        DBUG_PRINT("info", ("Initializing pattern: '%s'", first));
 
4527
        int *suff = (int*) thd->alloc((int) (sizeof(int)*
 
4528
                                      ((pattern_len + 1)*2+
 
4529
                                      alphabet_size)));
 
4530
        bmGs      = suff + pattern_len + 1;
 
4531
        bmBc      = bmGs + pattern_len + 1;
 
4532
        turboBM_compute_good_suffix_shifts(suff);
 
4533
        turboBM_compute_bad_character_shifts();
 
4534
        DBUG_PRINT("info",("done"));
 
4535
      }
 
4536
    }
 
4537
  }
 
4538
  return FALSE;
 
4539
}
 
4540
 
 
4541
void Item_func_like::cleanup()
 
4542
{
 
4543
  canDoTurboBM= FALSE;
 
4544
  Item_bool_func2::cleanup();
 
4545
}
 
4546
 
 
4547
#ifdef LIKE_CMP_TOUPPER
 
4548
#define likeconv(cs,A) (uchar) (cs)->toupper(A)
 
4549
#else
 
4550
#define likeconv(cs,A) (uchar) (cs)->sort_order[(uchar) (A)]
 
4551
#endif
 
4552
 
 
4553
 
 
4554
/**
 
4555
  Precomputation dependent only on pattern_len.
 
4556
*/
 
4557
 
 
4558
void Item_func_like::turboBM_compute_suffixes(int *suff)
 
4559
{
 
4560
  const int   plm1 = pattern_len - 1;
 
4561
  int            f = 0;
 
4562
  int            g = plm1;
 
4563
  int *const splm1 = suff + plm1;
 
4564
  CHARSET_INFO  *cs= cmp.cmp_collation.collation;
 
4565
 
 
4566
  *splm1 = pattern_len;
 
4567
 
 
4568
  if (!cs->sort_order)
 
4569
  {
 
4570
    int i;
 
4571
    for (i = pattern_len - 2; i >= 0; i--)
 
4572
    {
 
4573
      int tmp = *(splm1 + i - f);
 
4574
      if (g < i && tmp < i - g)
 
4575
        suff[i] = tmp;
 
4576
      else
 
4577
      {
 
4578
        if (i < g)
 
4579
          g = i; // g = min(i, g)
 
4580
        f = i;
 
4581
        while (g >= 0 && pattern[g] == pattern[g + plm1 - f])
 
4582
          g--;
 
4583
        suff[i] = f - g;
 
4584
      }
 
4585
    }
 
4586
  }
 
4587
  else
 
4588
  {
 
4589
    int i;
 
4590
    for (i = pattern_len - 2; 0 <= i; --i)
 
4591
    {
 
4592
      int tmp = *(splm1 + i - f);
 
4593
      if (g < i && tmp < i - g)
 
4594
        suff[i] = tmp;
 
4595
      else
 
4596
      {
 
4597
        if (i < g)
 
4598
          g = i; // g = min(i, g)
 
4599
        f = i;
 
4600
        while (g >= 0 &&
 
4601
               likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f]))
 
4602
          g--;
 
4603
        suff[i] = f - g;
 
4604
      }
 
4605
    }
 
4606
  }
 
4607
}
 
4608
 
 
4609
 
 
4610
/**
 
4611
  Precomputation dependent only on pattern_len.
 
4612
*/
 
4613
 
 
4614
void Item_func_like::turboBM_compute_good_suffix_shifts(int *suff)
 
4615
{
 
4616
  turboBM_compute_suffixes(suff);
 
4617
 
 
4618
  int *end = bmGs + pattern_len;
 
4619
  int *k;
 
4620
  for (k = bmGs; k < end; k++)
 
4621
    *k = pattern_len;
 
4622
 
 
4623
  int tmp;
 
4624
  int i;
 
4625
  int j          = 0;
 
4626
  const int plm1 = pattern_len - 1;
 
4627
  for (i = plm1; i > -1; i--)
 
4628
  {
 
4629
    if (suff[i] == i + 1)
 
4630
    {
 
4631
      for (tmp = plm1 - i; j < tmp; j++)
 
4632
      {
 
4633
        int *tmp2 = bmGs + j;
 
4634
        if (*tmp2 == pattern_len)
 
4635
          *tmp2 = tmp;
 
4636
      }
 
4637
    }
 
4638
  }
 
4639
 
 
4640
  int *tmp2;
 
4641
  for (tmp = plm1 - i; j < tmp; j++)
 
4642
  {
 
4643
    tmp2 = bmGs + j;
 
4644
    if (*tmp2 == pattern_len)
 
4645
      *tmp2 = tmp;
 
4646
  }
 
4647
 
 
4648
  tmp2 = bmGs + plm1;
 
4649
  for (i = 0; i <= pattern_len - 2; i++)
 
4650
    *(tmp2 - suff[i]) = plm1 - i;
 
4651
}
 
4652
 
 
4653
 
 
4654
/**
 
4655
   Precomputation dependent on pattern_len.
 
4656
*/
 
4657
 
 
4658
void Item_func_like::turboBM_compute_bad_character_shifts()
 
4659
{
 
4660
  int *i;
 
4661
  int *end = bmBc + alphabet_size;
 
4662
  int j;
 
4663
  const int plm1 = pattern_len - 1;
 
4664
  CHARSET_INFO  *cs= cmp.cmp_collation.collation;
 
4665
 
 
4666
  for (i = bmBc; i < end; i++)
 
4667
    *i = pattern_len;
 
4668
 
 
4669
  if (!cs->sort_order)
 
4670
  {
 
4671
    for (j = 0; j < plm1; j++)
 
4672
      bmBc[(uint) (uchar) pattern[j]] = plm1 - j;
 
4673
  }
 
4674
  else
 
4675
  {
 
4676
    for (j = 0; j < plm1; j++)
 
4677
      bmBc[(uint) likeconv(cs,pattern[j])] = plm1 - j;
 
4678
  }
 
4679
}
 
4680
 
 
4681
 
 
4682
/**
 
4683
  Search for pattern in text.
 
4684
 
 
4685
  @return
 
4686
    returns true/false for match/no match
 
4687
*/
 
4688
 
 
4689
bool Item_func_like::turboBM_matches(const char* text, int text_len) const
 
4690
{
 
4691
  register int bcShift;
 
4692
  register int turboShift;
 
4693
  int shift = pattern_len;
 
4694
  int j     = 0;
 
4695
  int u     = 0;
 
4696
  CHARSET_INFO  *cs= cmp.cmp_collation.collation;
 
4697
 
 
4698
  const int plm1=  pattern_len - 1;
 
4699
  const int tlmpl= text_len - pattern_len;
 
4700
 
 
4701
  /* Searching */
 
4702
  if (!cs->sort_order)
 
4703
  {
 
4704
    while (j <= tlmpl)
 
4705
    {
 
4706
      register int i= plm1;
 
4707
      while (i >= 0 && pattern[i] == text[i + j])
 
4708
      {
 
4709
        i--;
 
4710
        if (i == plm1 - shift)
 
4711
          i-= u;
 
4712
      }
 
4713
      if (i < 0)
 
4714
        return 1;
 
4715
 
 
4716
      register const int v = plm1 - i;
 
4717
      turboShift = u - v;
 
4718
      bcShift    = bmBc[(uint) (uchar) text[i + j]] - plm1 + i;
 
4719
      shift      = max(turboShift, bcShift);
 
4720
      shift      = max(shift, bmGs[i]);
 
4721
      if (shift == bmGs[i])
 
4722
        u = min(pattern_len - shift, v);
 
4723
      else
 
4724
      {
 
4725
        if (turboShift < bcShift)
 
4726
          shift = max(shift, u + 1);
 
4727
        u = 0;
 
4728
      }
 
4729
      j+= shift;
 
4730
    }
 
4731
    return 0;
 
4732
  }
 
4733
  else
 
4734
  {
 
4735
    while (j <= tlmpl)
 
4736
    {
 
4737
      register int i = plm1;
 
4738
      while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
 
4739
      {
 
4740
        i--;
 
4741
        if (i == plm1 - shift)
 
4742
          i-= u;
 
4743
      }
 
4744
      if (i < 0)
 
4745
        return 1;
 
4746
 
 
4747
      register const int v = plm1 - i;
 
4748
      turboShift = u - v;
 
4749
      bcShift    = bmBc[(uint) likeconv(cs, text[i + j])] - plm1 + i;
 
4750
      shift      = max(turboShift, bcShift);
 
4751
      shift      = max(shift, bmGs[i]);
 
4752
      if (shift == bmGs[i])
 
4753
        u = min(pattern_len - shift, v);
 
4754
      else
 
4755
      {
 
4756
        if (turboShift < bcShift)
 
4757
          shift = max(shift, u + 1);
 
4758
        u = 0;
 
4759
      }
 
4760
      j+= shift;
 
4761
    }
 
4762
    return 0;
 
4763
  }
 
4764
}
 
4765
 
 
4766
 
 
4767
/**
 
4768
  Make a logical XOR of the arguments.
 
4769
 
 
4770
  If either operator is NULL, return NULL.
 
4771
 
 
4772
  @todo
 
4773
    (low priority) Change this to be optimized as: @n
 
4774
    A XOR B   ->  (A) == 1 AND (B) <> 1) OR (A <> 1 AND (B) == 1) @n
 
4775
    To be able to do this, we would however first have to extend the MySQL
 
4776
    range optimizer to handle OR better.
 
4777
 
 
4778
  @note
 
4779
    As we don't do any index optimization on XOR this is not going to be
 
4780
    very fast to use.
 
4781
*/
 
4782
 
 
4783
longlong Item_cond_xor::val_int()
 
4784
{
 
4785
  DBUG_ASSERT(fixed == 1);
 
4786
  List_iterator<Item> li(list);
 
4787
  Item *item;
 
4788
  int result=0; 
 
4789
  null_value=0;
 
4790
  while ((item=li++))
 
4791
  {
 
4792
    result^= (item->val_int() != 0);
 
4793
    if (item->null_value)
 
4794
    {
 
4795
      null_value=1;
 
4796
      return 0;
 
4797
    }
 
4798
  }
 
4799
  return (longlong) result;
 
4800
}
 
4801
 
 
4802
/**
 
4803
  Apply NOT transformation to the item and return a new one.
 
4804
 
 
4805
 
 
4806
    Transform the item using next rules:
 
4807
    @verbatim
 
4808
       a AND b AND ...    -> NOT(a) OR NOT(b) OR ...
 
4809
       a OR b OR ...      -> NOT(a) AND NOT(b) AND ...
 
4810
       NOT(a)             -> a
 
4811
       a = b              -> a != b
 
4812
       a != b             -> a = b
 
4813
       a < b              -> a >= b
 
4814
       a >= b             -> a < b
 
4815
       a > b              -> a <= b
 
4816
       a <= b             -> a > b
 
4817
       IS NULL(a)         -> IS NOT NULL(a)
 
4818
       IS NOT NULL(a)     -> IS NULL(a)
 
4819
    @endverbatim
 
4820
 
 
4821
  @param thd            thread handler
 
4822
 
 
4823
  @return
 
4824
    New item or
 
4825
    NULL if we cannot apply NOT transformation (see Item::neg_transformer()).
 
4826
*/
 
4827
 
 
4828
Item *Item_func_not::neg_transformer(THD *thd)  /* NOT(x)  ->  x */
 
4829
{
 
4830
  return args[0];
 
4831
}
 
4832
 
 
4833
 
 
4834
Item *Item_bool_rowready_func2::neg_transformer(THD *thd)
 
4835
{
 
4836
  Item *item= negated_item();
 
4837
  return item;
 
4838
}
 
4839
 
 
4840
 
 
4841
/**
 
4842
  a IS NULL  ->  a IS NOT NULL.
 
4843
*/
 
4844
Item *Item_func_isnull::neg_transformer(THD *thd)
 
4845
{
 
4846
  Item *item= new Item_func_isnotnull(args[0]);
 
4847
  return item;
 
4848
}
 
4849
 
 
4850
 
 
4851
/**
 
4852
  a IS NOT NULL  ->  a IS NULL.
 
4853
*/
 
4854
Item *Item_func_isnotnull::neg_transformer(THD *thd)
 
4855
{
 
4856
  Item *item= new Item_func_isnull(args[0]);
 
4857
  return item;
 
4858
}
 
4859
 
 
4860
 
 
4861
Item *Item_cond_and::neg_transformer(THD *thd)  /* NOT(a AND b AND ...)  -> */
 
4862
                                        /* NOT a OR NOT b OR ... */
 
4863
{
 
4864
  neg_arguments(thd);
 
4865
  Item *item= new Item_cond_or(list);
 
4866
  return item;
 
4867
}
 
4868
 
 
4869
 
 
4870
Item *Item_cond_or::neg_transformer(THD *thd)   /* NOT(a OR b OR ...)  -> */
 
4871
                                        /* NOT a AND NOT b AND ... */
 
4872
{
 
4873
  neg_arguments(thd);
 
4874
  Item *item= new Item_cond_and(list);
 
4875
  return item;
 
4876
}
 
4877
 
 
4878
 
 
4879
Item *Item_func_nop_all::neg_transformer(THD *thd)
 
4880
{
 
4881
  /* "NOT (e $cmp$ ANY (SELECT ...)) -> e $rev_cmp$" ALL (SELECT ...) */
 
4882
  Item_func_not_all *new_item= new Item_func_not_all(args[0]);
 
4883
  Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
 
4884
  allany->func= allany->func_creator(FALSE);
 
4885
  allany->all= !allany->all;
 
4886
  allany->upper_item= new_item;
 
4887
  return new_item;
 
4888
}
 
4889
 
 
4890
Item *Item_func_not_all::neg_transformer(THD *thd)
 
4891
{
 
4892
  /* "NOT (e $cmp$ ALL (SELECT ...)) -> e $rev_cmp$" ANY (SELECT ...) */
 
4893
  Item_func_nop_all *new_item= new Item_func_nop_all(args[0]);
 
4894
  Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
 
4895
  allany->all= !allany->all;
 
4896
  allany->func= allany->func_creator(TRUE);
 
4897
  allany->upper_item= new_item;
 
4898
  return new_item;
 
4899
}
 
4900
 
 
4901
Item *Item_func_eq::negated_item()              /* a = b  ->  a != b */
 
4902
{
 
4903
  return new Item_func_ne(args[0], args[1]);
 
4904
}
 
4905
 
 
4906
 
 
4907
Item *Item_func_ne::negated_item()              /* a != b  ->  a = b */
 
4908
{
 
4909
  return new Item_func_eq(args[0], args[1]);
 
4910
}
 
4911
 
 
4912
 
 
4913
Item *Item_func_lt::negated_item()              /* a < b  ->  a >= b */
 
4914
{
 
4915
  return new Item_func_ge(args[0], args[1]);
 
4916
}
 
4917
 
 
4918
 
 
4919
Item *Item_func_ge::negated_item()              /* a >= b  ->  a < b */
 
4920
{
 
4921
  return new Item_func_lt(args[0], args[1]);
 
4922
}
 
4923
 
 
4924
 
 
4925
Item *Item_func_gt::negated_item()              /* a > b  ->  a <= b */
 
4926
{
 
4927
  return new Item_func_le(args[0], args[1]);
 
4928
}
 
4929
 
 
4930
 
 
4931
Item *Item_func_le::negated_item()              /* a <= b  ->  a > b */
 
4932
{
 
4933
  return new Item_func_gt(args[0], args[1]);
 
4934
}
 
4935
 
 
4936
/**
 
4937
  just fake method, should never be called.
 
4938
*/
 
4939
Item *Item_bool_rowready_func2::negated_item()
 
4940
{
 
4941
  DBUG_ASSERT(0);
 
4942
  return 0;
 
4943
}
 
4944
 
 
4945
Item_equal::Item_equal(Item_field *f1, Item_field *f2)
 
4946
  : Item_bool_func(), const_item(0), eval_item(0), cond_false(0)
 
4947
{
 
4948
  const_item_cache= 0;
 
4949
  fields.push_back(f1);
 
4950
  fields.push_back(f2);
 
4951
}
 
4952
 
 
4953
Item_equal::Item_equal(Item *c, Item_field *f)
 
4954
  : Item_bool_func(), eval_item(0), cond_false(0)
 
4955
{
 
4956
  const_item_cache= 0;
 
4957
  fields.push_back(f);
 
4958
  const_item= c;
 
4959
}
 
4960
 
 
4961
 
 
4962
Item_equal::Item_equal(Item_equal *item_equal)
 
4963
  : Item_bool_func(), eval_item(0), cond_false(0)
 
4964
{
 
4965
  const_item_cache= 0;
 
4966
  List_iterator_fast<Item_field> li(item_equal->fields);
 
4967
  Item_field *item;
 
4968
  while ((item= li++))
 
4969
  {
 
4970
    fields.push_back(item);
 
4971
  }
 
4972
  const_item= item_equal->const_item;
 
4973
  cond_false= item_equal->cond_false;
 
4974
}
 
4975
 
 
4976
void Item_equal::add(Item *c)
 
4977
{
 
4978
  if (cond_false)
 
4979
    return;
 
4980
  if (!const_item)
 
4981
  {
 
4982
    const_item= c;
 
4983
    return;
 
4984
  }
 
4985
  Item_func_eq *func= new Item_func_eq(c, const_item);
 
4986
  func->set_cmp_func();
 
4987
  func->quick_fix_field();
 
4988
  if ((cond_false= !func->val_int()))
 
4989
    const_item_cache= 1;
 
4990
}
 
4991
 
 
4992
void Item_equal::add(Item_field *f)
 
4993
{
 
4994
  fields.push_back(f);
 
4995
}
 
4996
 
 
4997
uint Item_equal::members()
 
4998
{
 
4999
  return fields.elements;
 
5000
}
 
5001
 
 
5002
 
 
5003
/**
 
5004
  Check whether a field is referred in the multiple equality.
 
5005
 
 
5006
  The function checks whether field is occurred in the Item_equal object .
 
5007
 
 
5008
  @param field   field whose occurrence is to be checked
 
5009
 
 
5010
  @retval
 
5011
    1       if nultiple equality contains a reference to field
 
5012
  @retval
 
5013
    0       otherwise    
 
5014
*/
 
5015
 
 
5016
bool Item_equal::contains(Field *field)
 
5017
{
 
5018
  List_iterator_fast<Item_field> it(fields);
 
5019
  Item_field *item;
 
5020
  while ((item= it++))
 
5021
  {
 
5022
    if (field->eq(item->field))
 
5023
        return 1;
 
5024
  }
 
5025
  return 0;
 
5026
}
 
5027
 
 
5028
 
 
5029
/**
 
5030
  Join members of another Item_equal object.
 
5031
  
 
5032
    The function actually merges two multiple equalities.
 
5033
    After this operation the Item_equal object additionally contains
 
5034
    the field items of another item of the type Item_equal.
 
5035
    If the optional constant items are not equal the cond_false flag is
 
5036
    set to 1.  
 
5037
  @param item    multiple equality whose members are to be joined
 
5038
*/
 
5039
 
 
5040
void Item_equal::merge(Item_equal *item)
 
5041
{
 
5042
  fields.concat(&item->fields);
 
5043
  Item *c= item->const_item;
 
5044
  if (c)
 
5045
  {
 
5046
    /* 
 
5047
      The flag cond_false will be set to 1 after this, if 
 
5048
      the multiple equality already contains a constant and its 
 
5049
      value is  not equal to the value of c.
 
5050
    */
 
5051
    add(c);
 
5052
  }
 
5053
  cond_false|= item->cond_false;
 
5054
 
5055
 
 
5056
 
 
5057
/**
 
5058
  Order field items in multiple equality according to a sorting criteria.
 
5059
 
 
5060
  The function perform ordering of the field items in the Item_equal
 
5061
  object according to the criteria determined by the cmp callback parameter.
 
5062
  If cmp(item_field1,item_field2,arg)<0 than item_field1 must be
 
5063
  placed after item_fiel2.
 
5064
 
 
5065
  The function sorts field items by the exchange sort algorithm.
 
5066
  The list of field items is looked through and whenever two neighboring
 
5067
  members follow in a wrong order they are swapped. This is performed
 
5068
  again and again until we get all members in a right order.
 
5069
 
 
5070
  @param cmp          function to compare field item
 
5071
  @param arg          context extra parameter for the cmp function
 
5072
*/
 
5073
 
 
5074
void Item_equal::sort(Item_field_cmpfunc cmp, void *arg)
 
5075
{
 
5076
  bool swap;
 
5077
  List_iterator<Item_field> it(fields);
 
5078
  do
 
5079
  {
 
5080
    Item_field *item1= it++;
 
5081
    Item_field **ref1= it.ref();
 
5082
    Item_field *item2;
 
5083
 
 
5084
    swap= FALSE;
 
5085
    while ((item2= it++))
 
5086
    {
 
5087
      Item_field **ref2= it.ref();
 
5088
      if (cmp(item1, item2, arg) < 0)
 
5089
      {
 
5090
        Item_field *item= *ref1;
 
5091
        *ref1= *ref2;
 
5092
        *ref2= item;
 
5093
        swap= TRUE;
 
5094
      }
 
5095
      else
 
5096
      {
 
5097
        item1= item2;
 
5098
        ref1= ref2;
 
5099
      }
 
5100
    }
 
5101
    it.rewind();
 
5102
  } while (swap);
 
5103
}
 
5104
 
 
5105
 
 
5106
/**
 
5107
  Check appearance of new constant items in the multiple equality object.
 
5108
 
 
5109
  The function checks appearance of new constant items among
 
5110
  the members of multiple equalities. Each new constant item is
 
5111
  compared with the designated constant item if there is any in the
 
5112
  multiple equality. If there is none the first new constant item
 
5113
  becomes designated.
 
5114
*/
 
5115
 
 
5116
void Item_equal::update_const()
 
5117
{
 
5118
  List_iterator<Item_field> it(fields);
 
5119
  Item *item;
 
5120
  while ((item= it++))
 
5121
  {
 
5122
    if (item->const_item())
 
5123
    {
 
5124
      it.remove();
 
5125
      add(item);
 
5126
    }
 
5127
  }
 
5128
}
 
5129
 
 
5130
bool Item_equal::fix_fields(THD *thd, Item **ref)
 
5131
{
 
5132
  List_iterator_fast<Item_field> li(fields);
 
5133
  Item *item;
 
5134
  not_null_tables_cache= used_tables_cache= 0;
 
5135
  const_item_cache= 0;
 
5136
  while ((item= li++))
 
5137
  {
 
5138
    table_map tmp_table_map;
 
5139
    used_tables_cache|= item->used_tables();
 
5140
    tmp_table_map= item->not_null_tables();
 
5141
    not_null_tables_cache|= tmp_table_map;
 
5142
    if (item->maybe_null)
 
5143
      maybe_null=1;
 
5144
  }
 
5145
  fix_length_and_dec();
 
5146
  fixed= 1;
 
5147
  return 0;
 
5148
}
 
5149
 
 
5150
void Item_equal::update_used_tables()
 
5151
{
 
5152
  List_iterator_fast<Item_field> li(fields);
 
5153
  Item *item;
 
5154
  not_null_tables_cache= used_tables_cache= 0;
 
5155
  if ((const_item_cache= cond_false))
 
5156
    return;
 
5157
  while ((item=li++))
 
5158
  {
 
5159
    item->update_used_tables();
 
5160
    used_tables_cache|= item->used_tables();
 
5161
    const_item_cache&= item->const_item();
 
5162
  }
 
5163
}
 
5164
 
 
5165
longlong Item_equal::val_int()
 
5166
{
 
5167
  Item_field *item_field;
 
5168
  if (cond_false)
 
5169
    return 0;
 
5170
  List_iterator_fast<Item_field> it(fields);
 
5171
  Item *item= const_item ? const_item : it++;
 
5172
  if ((null_value= item->null_value))
 
5173
    return 0;
 
5174
  eval_item->store_value(item);
 
5175
  while ((item_field= it++))
 
5176
  {
 
5177
    /* Skip fields of non-const tables. They haven't been read yet */
 
5178
    if (item_field->field->table->const_table)
 
5179
    {
 
5180
      if ((null_value= item_field->null_value) || eval_item->cmp(item_field))
 
5181
        return 0;
 
5182
    }
 
5183
  }
 
5184
  return 1;
 
5185
}
 
5186
 
 
5187
void Item_equal::fix_length_and_dec()
 
5188
{
 
5189
  Item *item= get_first();
 
5190
  eval_item= cmp_item::get_comparator(item->result_type(),
 
5191
                                      item->collation.collation);
 
5192
}
 
5193
 
 
5194
bool Item_equal::walk(Item_processor processor, bool walk_subquery, uchar *arg)
 
5195
{
 
5196
  List_iterator_fast<Item_field> it(fields);
 
5197
  Item *item;
 
5198
  while ((item= it++))
 
5199
  {
 
5200
    if (item->walk(processor, walk_subquery, arg))
 
5201
      return 1;
 
5202
  }
 
5203
  return Item_func::walk(processor, walk_subquery, arg);
 
5204
}
 
5205
 
 
5206
Item *Item_equal::transform(Item_transformer transformer, uchar *arg)
 
5207
{
 
5208
  List_iterator<Item_field> it(fields);
 
5209
  Item *item;
 
5210
  while ((item= it++))
 
5211
  {
 
5212
    Item *new_item= item->transform(transformer, arg);
 
5213
    if (!new_item)
 
5214
      return 0;
 
5215
 
 
5216
    /*
 
5217
      THD::change_item_tree() should be called only if the tree was
 
5218
      really transformed, i.e. when a new item has been created.
 
5219
      Otherwise we'll be allocating a lot of unnecessary memory for
 
5220
      change records at each execution.
 
5221
    */
 
5222
    if (new_item != item)
 
5223
      current_thd->change_item_tree((Item **) it.ref(), new_item);
 
5224
  }
 
5225
  return Item_func::transform(transformer, arg);
 
5226
}
 
5227
 
 
5228
void Item_equal::print(String *str, enum_query_type query_type)
 
5229
{
 
5230
  str->append(func_name());
 
5231
  str->append('(');
 
5232
  List_iterator_fast<Item_field> it(fields);
 
5233
  Item *item;
 
5234
  if (const_item)
 
5235
    const_item->print(str, query_type);
 
5236
  else
 
5237
  {
 
5238
    item= it++;
 
5239
    item->print(str, query_type);
 
5240
  }
 
5241
  while ((item= it++))
 
5242
  {
 
5243
    str->append(',');
 
5244
    str->append(' ');
 
5245
    item->print(str, query_type);
 
5246
  }
 
5247
  str->append(')');
 
5248
}
 
5249