~ubuntu-branches/ubuntu/saucy/drizzle/saucy-proposed

« back to all changes in this revision

Viewing changes to drizzled/item/cmpfunc.cc

  • Committer: Bazaar Package Importer
  • Author(s): Monty Taylor
  • Date: 2010-03-18 12:12:31 UTC
  • Revision ID: james.westby@ubuntu.com-20100318121231-k6g1xe6cshbwa0f8
Tags: upstream-2010.03.1347
ImportĀ upstreamĀ versionĀ 2010.03.1347

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