~drizzle-trunk/drizzle/development

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