~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/item_cmpfunc.cc

  • Committer: Monty Taylor
  • Date: 2008-07-28 02:47:38 UTC
  • mto: (212.5.1 codestyle)
  • mto: This revision was merged to the branch mainline in revision 219.
  • Revision ID: monty@inaugust.com-20080728024738-366ikqnoqv7d8g6l
Fixed the includes in places to make the myisam header file move work.

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