~ubuntu-branches/ubuntu/precise/mysql-5.1/precise

« back to all changes in this revision

Viewing changes to sql/item_cmpfunc.cc

  • Committer: Bazaar Package Importer
  • Author(s): Norbert Tretkowski
  • Date: 2010-03-17 14:56:02 UTC
  • Revision ID: james.westby@ubuntu.com-20100317145602-x7e30l1b2sb5s6w6
Tags: upstream-5.1.45
ImportĀ upstreamĀ versionĀ 5.1.45

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