~linuxjedi/drizzle/trunk-bug-667053

« back to all changes in this revision

Viewing changes to sql/item_strfunc.cc

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Copyright (C) 2000-2006 MySQL AB
 
2
 
 
3
   This program is free software; you can redistribute it and/or modify
 
4
   it under the terms of the GNU General Public License as published by
 
5
   the Free Software Foundation; version 2 of the License.
 
6
 
 
7
   This program is distributed in the hope that it will be useful,
 
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
   GNU General Public License for more details.
 
11
 
 
12
   You should have received a copy of the GNU General Public License
 
13
   along with this program; if not, write to the Free Software
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
15
 
 
16
 
 
17
/**
 
18
  @file
 
19
 
 
20
  @brief
 
21
  This file defines all string functions
 
22
 
 
23
  @warning
 
24
    Some string functions don't always put and end-null on a String.
 
25
    (This shouldn't be needed)
 
26
*/
 
27
 
 
28
#ifdef USE_PRAGMA_IMPLEMENTATION
 
29
#pragma implementation                          // gcc: Class implementation
 
30
#endif
 
31
 
 
32
 
 
33
#include "mysql_priv.h"
 
34
#include <m_ctype.h>
 
35
#include "my_md5.h"
 
36
#include "sha1.h"
 
37
#include "sha2.h"
 
38
#include <zlib.h>
 
39
C_MODE_START
 
40
#include "../mysys/my_static.h"                 // For soundex_map
 
41
C_MODE_END
 
42
 
 
43
String my_empty_string("",default_charset_info);
 
44
 
 
45
 
 
46
 
 
47
 
 
48
bool Item_str_func::fix_fields(THD *thd, Item **ref)
 
49
{
 
50
  bool res= Item_func::fix_fields(thd, ref);
 
51
  /*
 
52
    In Item_str_func::check_well_formed_result() we may set null_value
 
53
    flag on the same condition as in test() below.
 
54
  */
 
55
  maybe_null= (maybe_null ||
 
56
               test(thd->variables.sql_mode &
 
57
                    (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)));
 
58
  return res;
 
59
}
 
60
 
 
61
 
 
62
my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
 
63
{
 
64
  DBUG_ASSERT(fixed == 1);
 
65
  char buff[64];
 
66
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
 
67
  res= val_str(&tmp);
 
68
  if (!res)
 
69
    return 0;
 
70
  (void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
 
71
                       res->length(), res->charset(), decimal_value);
 
72
  return decimal_value;
 
73
}
 
74
 
 
75
 
 
76
double Item_str_func::val_real()
 
77
{
 
78
  DBUG_ASSERT(fixed == 1);
 
79
  int err_not_used;
 
80
  char *end_not_used, buff[64];
 
81
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
 
82
  res= val_str(&tmp);
 
83
  return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
 
84
                          &end_not_used, &err_not_used) : 0.0;
 
85
}
 
86
 
 
87
 
 
88
longlong Item_str_func::val_int()
 
89
{
 
90
  DBUG_ASSERT(fixed == 1);
 
91
  int err;
 
92
  char buff[22];
 
93
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
 
94
  res= val_str(&tmp);
 
95
  return (res ?
 
96
          my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL,
 
97
                      &err) :
 
98
          (longlong) 0);
 
99
}
 
100
 
 
101
 
 
102
String *Item_func_md5::val_str(String *str)
 
103
{
 
104
  DBUG_ASSERT(fixed == 1);
 
105
  String * sptr= args[0]->val_str(str);
 
106
  str->set_charset(&my_charset_bin);
 
107
  if (sptr)
 
108
  {
 
109
    my_MD5_CTX context;
 
110
    uchar digest[16];
 
111
 
 
112
    null_value=0;
 
113
    my_MD5Init (&context);
 
114
    my_MD5Update (&context,(uchar *) sptr->ptr(), sptr->length());
 
115
    my_MD5Final (digest, &context);
 
116
    if (str->alloc(32))                         // Ensure that memory is free
 
117
    {
 
118
      null_value=1;
 
119
      return 0;
 
120
    }
 
121
    sprintf((char *) str->ptr(),
 
122
            "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
 
123
            digest[0], digest[1], digest[2], digest[3],
 
124
            digest[4], digest[5], digest[6], digest[7],
 
125
            digest[8], digest[9], digest[10], digest[11],
 
126
            digest[12], digest[13], digest[14], digest[15]);
 
127
    str->length((uint) 32);
 
128
    return str;
 
129
  }
 
130
  null_value=1;
 
131
  return 0;
 
132
}
 
133
 
 
134
 
 
135
void Item_func_md5::fix_length_and_dec()
 
136
{
 
137
  max_length=32;
 
138
  /*
 
139
    The MD5() function treats its parameter as being a case sensitive. Thus
 
140
    we set binary collation on it so different instances of MD5() will be
 
141
    compared properly.
 
142
  */
 
143
  args[0]->collation.set(
 
144
      get_charset_by_csname(args[0]->collation.collation->csname,
 
145
                            MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
 
146
}
 
147
 
 
148
/**
 
149
  Concatenate args with the following premises:
 
150
  If only one arg (which is ok), return value of arg;
 
151
  Don't reallocate val_str() if not absolute necessary.
 
152
*/
 
153
 
 
154
String *Item_func_concat::val_str(String *str)
 
155
{
 
156
  DBUG_ASSERT(fixed == 1);
 
157
  String *res,*res2,*use_as_buff;
 
158
  uint i;
 
159
  bool is_const= 0;
 
160
 
 
161
  null_value=0;
 
162
  if (!(res=args[0]->val_str(str)))
 
163
    goto null;
 
164
  use_as_buff= &tmp_value;
 
165
  /* Item_subselect in --ps-protocol mode will state it as a non-const */
 
166
  is_const= args[0]->const_item() || !args[0]->used_tables();
 
167
  for (i=1 ; i < arg_count ; i++)
 
168
  {
 
169
    if (res->length() == 0)
 
170
    {
 
171
      if (!(res=args[i]->val_str(str)))
 
172
        goto null;
 
173
    }
 
174
    else
 
175
    {
 
176
      if (!(res2=args[i]->val_str(use_as_buff)))
 
177
        goto null;
 
178
      if (res2->length() == 0)
 
179
        continue;
 
180
      if (res->length()+res2->length() >
 
181
          current_thd->variables.max_allowed_packet)
 
182
      {
 
183
        push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
184
                            ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
185
                            ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
 
186
                            current_thd->variables.max_allowed_packet);
 
187
        goto null;
 
188
      }
 
189
      if (!is_const && res->alloced_length() >= res->length()+res2->length())
 
190
      {                                         // Use old buffer
 
191
        res->append(*res2);
 
192
      }
 
193
      else if (str->alloced_length() >= res->length()+res2->length())
 
194
      {
 
195
        if (str == res2)
 
196
          str->replace(0,0,*res);
 
197
        else
 
198
        {
 
199
          str->copy(*res);
 
200
          str->append(*res2);
 
201
        }
 
202
        res= str;
 
203
        use_as_buff= &tmp_value;
 
204
      }
 
205
      else if (res == &tmp_value)
 
206
      {
 
207
        if (res->append(*res2))                 // Must be a blob
 
208
          goto null;
 
209
      }
 
210
      else if (res2 == &tmp_value)
 
211
      {                                         // This can happend only 1 time
 
212
        if (tmp_value.replace(0,0,*res))
 
213
          goto null;
 
214
        res= &tmp_value;
 
215
        use_as_buff=str;                        // Put next arg here
 
216
      }
 
217
      else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
 
218
               res2->ptr() <= tmp_value.ptr() + tmp_value.alloced_length())
 
219
      {
 
220
        /*
 
221
          This happens really seldom:
 
222
          In this case res2 is sub string of tmp_value.  We will
 
223
          now work in place in tmp_value to set it to res | res2
 
224
        */
 
225
        /* Chop the last characters in tmp_value that isn't in res2 */
 
226
        tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
 
227
                         res2->length());
 
228
        /* Place res2 at start of tmp_value, remove chars before res2 */
 
229
        if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
 
230
                              *res))
 
231
          goto null;
 
232
        res= &tmp_value;
 
233
        use_as_buff=str;                        // Put next arg here
 
234
      }
 
235
      else
 
236
      {                                         // Two big const strings
 
237
        /*
 
238
          NOTE: We should be prudent in the initial allocation unit -- the
 
239
          size of the arguments is a function of data distribution, which
 
240
          can be any. Instead of overcommitting at the first row, we grow
 
241
          the allocated amount by the factor of 2. This ensures that no
 
242
          more than 25% of memory will be overcommitted on average.
 
243
        */
 
244
 
 
245
        uint concat_len= res->length() + res2->length();
 
246
 
 
247
        if (tmp_value.alloced_length() < concat_len)
 
248
        {
 
249
          if (tmp_value.alloced_length() == 0)
 
250
          {
 
251
            if (tmp_value.alloc(concat_len))
 
252
              goto null;
 
253
          }
 
254
          else
 
255
          {
 
256
            uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
 
257
 
 
258
            if (tmp_value.realloc(new_len))
 
259
              goto null;
 
260
          }
 
261
        }
 
262
 
 
263
        if (tmp_value.copy(*res) || tmp_value.append(*res2))
 
264
          goto null;
 
265
 
 
266
        res= &tmp_value;
 
267
        use_as_buff=str;
 
268
      }
 
269
      is_const= 0;
 
270
    }
 
271
  }
 
272
  res->set_charset(collation.collation);
 
273
  return res;
 
274
 
 
275
null:
 
276
  null_value=1;
 
277
  return 0;
 
278
}
 
279
 
 
280
 
 
281
void Item_func_concat::fix_length_and_dec()
 
282
{
 
283
  ulonglong max_result_length= 0;
 
284
 
 
285
  if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
 
286
    return;
 
287
 
 
288
  for (uint i=0 ; i < arg_count ; i++)
 
289
  {
 
290
    if (args[i]->collation.collation->mbmaxlen != collation.collation->mbmaxlen)
 
291
      max_result_length+= (args[i]->max_length /
 
292
                           args[i]->collation.collation->mbmaxlen) *
 
293
                           collation.collation->mbmaxlen;
 
294
    else
 
295
      max_result_length+= args[i]->max_length;
 
296
  }
 
297
 
 
298
  if (max_result_length >= MAX_BLOB_WIDTH)
 
299
  {
 
300
    max_result_length= MAX_BLOB_WIDTH;
 
301
    maybe_null= 1;
 
302
  }
 
303
  max_length= (ulong) max_result_length;
 
304
}
 
305
 
 
306
 
 
307
/**
 
308
  concat with separator. First arg is the separator
 
309
  concat_ws takes at least two arguments.
 
310
*/
 
311
 
 
312
String *Item_func_concat_ws::val_str(String *str)
 
313
{
 
314
  DBUG_ASSERT(fixed == 1);
 
315
  char tmp_str_buff[10];
 
316
  String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
 
317
         *sep_str, *res, *res2,*use_as_buff;
 
318
  uint i;
 
319
 
 
320
  null_value=0;
 
321
  if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
 
322
    goto null;
 
323
 
 
324
  use_as_buff= &tmp_value;
 
325
  str->length(0);                               // QQ; Should be removed
 
326
  res=str;
 
327
 
 
328
  // Skip until non-null argument is found.
 
329
  // If not, return the empty string
 
330
  for (i=1; i < arg_count; i++)
 
331
    if ((res= args[i]->val_str(str)))
 
332
      break;
 
333
  if (i ==  arg_count)
 
334
    return &my_empty_string;
 
335
 
 
336
  for (i++; i < arg_count ; i++)
 
337
  {
 
338
    if (!(res2= args[i]->val_str(use_as_buff)))
 
339
      continue;                                 // Skip NULL
 
340
 
 
341
    if (res->length() + sep_str->length() + res2->length() >
 
342
        current_thd->variables.max_allowed_packet)
 
343
    {
 
344
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
345
                          ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
346
                          ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
 
347
                          current_thd->variables.max_allowed_packet);
 
348
      goto null;
 
349
    }
 
350
    if (res->alloced_length() >=
 
351
        res->length() + sep_str->length() + res2->length())
 
352
    {                                           // Use old buffer
 
353
      res->append(*sep_str);                    // res->length() > 0 always
 
354
      res->append(*res2);
 
355
    }
 
356
    else if (str->alloced_length() >=
 
357
             res->length() + sep_str->length() + res2->length())
 
358
    {
 
359
      /* We have room in str;  We can't get any errors here */
 
360
      if (str == res2)
 
361
      {                                         // This is quote uncommon!
 
362
        str->replace(0,0,*sep_str);
 
363
        str->replace(0,0,*res);
 
364
      }
 
365
      else
 
366
      {
 
367
        str->copy(*res);
 
368
        str->append(*sep_str);
 
369
        str->append(*res2);
 
370
      }
 
371
      res=str;
 
372
      use_as_buff= &tmp_value;
 
373
    }
 
374
    else if (res == &tmp_value)
 
375
    {
 
376
      if (res->append(*sep_str) || res->append(*res2))
 
377
        goto null; // Must be a blob
 
378
    }
 
379
    else if (res2 == &tmp_value)
 
380
    {                                           // This can happend only 1 time
 
381
      if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res))
 
382
        goto null;
 
383
      res= &tmp_value;
 
384
      use_as_buff=str;                          // Put next arg here
 
385
    }
 
386
    else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
 
387
             res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
 
388
    {
 
389
      /*
 
390
        This happens really seldom:
 
391
        In this case res2 is sub string of tmp_value.  We will
 
392
        now work in place in tmp_value to set it to res | sep_str | res2
 
393
      */
 
394
      /* Chop the last characters in tmp_value that isn't in res2 */
 
395
      tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
 
396
                       res2->length());
 
397
      /* Place res2 at start of tmp_value, remove chars before res2 */
 
398
      if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
 
399
                            *res) ||
 
400
          tmp_value.replace(res->length(),0, *sep_str))
 
401
        goto null;
 
402
      res= &tmp_value;
 
403
      use_as_buff=str;                  // Put next arg here
 
404
    }
 
405
    else
 
406
    {                                           // Two big const strings
 
407
      /*
 
408
        NOTE: We should be prudent in the initial allocation unit -- the
 
409
        size of the arguments is a function of data distribution, which can
 
410
        be any. Instead of overcommitting at the first row, we grow the
 
411
        allocated amount by the factor of 2. This ensures that no more than
 
412
        25% of memory will be overcommitted on average.
 
413
      */
 
414
 
 
415
      uint concat_len= res->length() + sep_str->length() + res2->length();
 
416
 
 
417
      if (tmp_value.alloced_length() < concat_len)
 
418
      {
 
419
        if (tmp_value.alloced_length() == 0)
 
420
        {
 
421
          if (tmp_value.alloc(concat_len))
 
422
            goto null;
 
423
        }
 
424
        else
 
425
        {
 
426
          uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
 
427
 
 
428
          if (tmp_value.realloc(new_len))
 
429
            goto null;
 
430
        }
 
431
      }
 
432
 
 
433
      if (tmp_value.copy(*res) ||
 
434
          tmp_value.append(*sep_str) ||
 
435
          tmp_value.append(*res2))
 
436
        goto null;
 
437
      res= &tmp_value;
 
438
      use_as_buff=str;
 
439
    }
 
440
  }
 
441
  res->set_charset(collation.collation);
 
442
  return res;
 
443
 
 
444
null:
 
445
  null_value=1;
 
446
  return 0;
 
447
}
 
448
 
 
449
 
 
450
void Item_func_concat_ws::fix_length_and_dec()
 
451
{
 
452
  ulonglong max_result_length;
 
453
 
 
454
  if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
 
455
    return;
 
456
 
 
457
  /*
 
458
     arg_count cannot be less than 2,
 
459
     it is done on parser level in sql_yacc.yy
 
460
     so, (arg_count - 2) is safe here.
 
461
  */
 
462
  max_result_length= (ulonglong) args[0]->max_length * (arg_count - 2);
 
463
  for (uint i=1 ; i < arg_count ; i++)
 
464
    max_result_length+=args[i]->max_length;
 
465
 
 
466
  if (max_result_length >= MAX_BLOB_WIDTH)
 
467
  {
 
468
    max_result_length= MAX_BLOB_WIDTH;
 
469
    maybe_null= 1;
 
470
  }
 
471
  max_length= (ulong) max_result_length;
 
472
}
 
473
 
 
474
 
 
475
String *Item_func_reverse::val_str(String *str)
 
476
{
 
477
  DBUG_ASSERT(fixed == 1);
 
478
  String *res = args[0]->val_str(str);
 
479
  char *ptr, *end, *tmp;
 
480
 
 
481
  if ((null_value=args[0]->null_value))
 
482
    return 0;
 
483
  /* An empty string is a special case as the string pointer may be null */
 
484
  if (!res->length())
 
485
    return &my_empty_string;
 
486
  if (tmp_value.alloced_length() < res->length() &&
 
487
      tmp_value.realloc(res->length()))
 
488
  {
 
489
    null_value= 1;
 
490
    return 0;
 
491
  }
 
492
  tmp_value.length(res->length());
 
493
  tmp_value.set_charset(res->charset());
 
494
  ptr= (char *) res->ptr();
 
495
  end= ptr + res->length();
 
496
  tmp= (char *) tmp_value.ptr() + tmp_value.length();
 
497
#ifdef USE_MB
 
498
  if (use_mb(res->charset()))
 
499
  {
 
500
    register uint32 l;
 
501
    while (ptr < end)
 
502
    {
 
503
      if ((l= my_ismbchar(res->charset(),ptr,end)))
 
504
      {
 
505
        tmp-= l;
 
506
        memcpy(tmp,ptr,l);
 
507
        ptr+= l;
 
508
      }
 
509
      else
 
510
        *--tmp= *ptr++;
 
511
    }
 
512
  }
 
513
  else
 
514
#endif /* USE_MB */
 
515
  {
 
516
    while (ptr < end)
 
517
      *--tmp= *ptr++;
 
518
  }
 
519
  return &tmp_value;
 
520
}
 
521
 
 
522
 
 
523
void Item_func_reverse::fix_length_and_dec()
 
524
{
 
525
  collation.set(args[0]->collation);
 
526
  max_length = args[0]->max_length;
 
527
}
 
528
 
 
529
/**
 
530
  Replace all occurences of string2 in string1 with string3.
 
531
 
 
532
  Don't reallocate val_str() if not needed.
 
533
 
 
534
  @todo
 
535
    Fix that this works with binary strings when using USE_MB 
 
536
*/
 
537
 
 
538
String *Item_func_replace::val_str(String *str)
 
539
{
 
540
  DBUG_ASSERT(fixed == 1);
 
541
  String *res,*res2,*res3;
 
542
  int offset;
 
543
  uint from_length,to_length;
 
544
  bool alloced=0;
 
545
#ifdef USE_MB
 
546
  const char *ptr,*end,*strend,*search,*search_end;
 
547
  register uint32 l;
 
548
  bool binary_cmp;
 
549
#endif
 
550
 
 
551
  null_value=0;
 
552
  res=args[0]->val_str(str);
 
553
  if (args[0]->null_value)
 
554
    goto null;
 
555
  res2=args[1]->val_str(&tmp_value);
 
556
  if (args[1]->null_value)
 
557
    goto null;
 
558
 
 
559
  res->set_charset(collation.collation);
 
560
 
 
561
#ifdef USE_MB
 
562
  binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
 
563
#endif
 
564
 
 
565
  if (res2->length() == 0)
 
566
    return res;
 
567
#ifndef USE_MB
 
568
  if ((offset=res->strstr(*res2)) < 0)
 
569
    return res;
 
570
#else
 
571
  offset=0;
 
572
  if (binary_cmp && (offset=res->strstr(*res2)) < 0)
 
573
    return res;
 
574
#endif
 
575
  if (!(res3=args[2]->val_str(&tmp_value2)))
 
576
    goto null;
 
577
  from_length= res2->length();
 
578
  to_length=   res3->length();
 
579
 
 
580
#ifdef USE_MB
 
581
  if (!binary_cmp)
 
582
  {
 
583
    search=res2->ptr();
 
584
    search_end=search+from_length;
 
585
redo:
 
586
    ptr=res->ptr()+offset;
 
587
    strend=res->ptr()+res->length();
 
588
    end=strend-from_length+1;
 
589
    while (ptr < end)
 
590
    {
 
591
        if (*ptr == *search)
 
592
        {
 
593
          register char *i,*j;
 
594
          i=(char*) ptr+1; j=(char*) search+1;
 
595
          while (j != search_end)
 
596
            if (*i++ != *j++) goto skip;
 
597
          offset= (int) (ptr-res->ptr());
 
598
          if (res->length()-from_length + to_length >
 
599
              current_thd->variables.max_allowed_packet)
 
600
          {
 
601
            push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
602
                                ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
603
                                ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
604
                                func_name(),
 
605
                                current_thd->variables.max_allowed_packet);
 
606
 
 
607
            goto null;
 
608
          }
 
609
          if (!alloced)
 
610
          {
 
611
            alloced=1;
 
612
            res=copy_if_not_alloced(str,res,res->length()+to_length);
 
613
          }
 
614
          res->replace((uint) offset,from_length,*res3);
 
615
          offset+=(int) to_length;
 
616
          goto redo;
 
617
        }
 
618
skip:
 
619
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
 
620
        else ++ptr;
 
621
    }
 
622
  }
 
623
  else
 
624
#endif /* USE_MB */
 
625
    do
 
626
    {
 
627
      if (res->length()-from_length + to_length >
 
628
          current_thd->variables.max_allowed_packet)
 
629
      {
 
630
        push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
631
                            ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
632
                            ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
 
633
                            current_thd->variables.max_allowed_packet);
 
634
        goto null;
 
635
      }
 
636
      if (!alloced)
 
637
      {
 
638
        alloced=1;
 
639
        res=copy_if_not_alloced(str,res,res->length()+to_length);
 
640
      }
 
641
      res->replace((uint) offset,from_length,*res3);
 
642
      offset+=(int) to_length;
 
643
    }
 
644
    while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
 
645
  return res;
 
646
 
 
647
null:
 
648
  null_value=1;
 
649
  return 0;
 
650
}
 
651
 
 
652
 
 
653
void Item_func_replace::fix_length_and_dec()
 
654
{
 
655
  ulonglong max_result_length= args[0]->max_length;
 
656
  int diff=(int) (args[2]->max_length - args[1]->max_length);
 
657
  if (diff > 0 && args[1]->max_length)
 
658
  {                                             // Calculate of maxreplaces
 
659
    ulonglong max_substrs= max_result_length/args[1]->max_length;
 
660
    max_result_length+= max_substrs * (uint) diff;
 
661
  }
 
662
  if (max_result_length >= MAX_BLOB_WIDTH)
 
663
  {
 
664
    max_result_length= MAX_BLOB_WIDTH;
 
665
    maybe_null= 1;
 
666
  }
 
667
  max_length= (ulong) max_result_length;
 
668
  
 
669
  if (agg_arg_charsets(collation, args, 3, MY_COLL_CMP_CONV, 1))
 
670
    return;
 
671
}
 
672
 
 
673
 
 
674
String *Item_func_insert::val_str(String *str)
 
675
{
 
676
  DBUG_ASSERT(fixed == 1);
 
677
  String *res,*res2;
 
678
  longlong start, length;  /* must be longlong to avoid truncation */
 
679
 
 
680
  null_value=0;
 
681
  res=args[0]->val_str(str);
 
682
  res2=args[3]->val_str(&tmp_value);
 
683
  start= args[1]->val_int() - 1;
 
684
  length= args[2]->val_int();
 
685
 
 
686
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
 
687
      args[3]->null_value)
 
688
    goto null; /* purecov: inspected */
 
689
 
 
690
  if ((start < 0) || (start > res->length()))
 
691
    return res;                                 // Wrong param; skip insert
 
692
  if ((length < 0) || (length > res->length()))
 
693
    length= res->length();
 
694
 
 
695
  /* start and length are now sufficiently valid to pass to charpos function */
 
696
   start= res->charpos((int) start);
 
697
   length= res->charpos((int) length, (uint32) start);
 
698
 
 
699
  /* Re-testing with corrected params */
 
700
  if (start > res->length())
 
701
    return res; /* purecov: inspected */        // Wrong param; skip insert
 
702
  if (length > res->length() - start)
 
703
    length= res->length() - start;
 
704
 
 
705
  if ((ulonglong) (res->length() - length + res2->length()) >
 
706
      (ulonglong) current_thd->variables.max_allowed_packet)
 
707
  {
 
708
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
709
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
710
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
711
                        func_name(), current_thd->variables.max_allowed_packet);
 
712
    goto null;
 
713
  }
 
714
  res=copy_if_not_alloced(str,res,res->length());
 
715
  res->replace((uint32) start,(uint32) length,*res2);
 
716
  return res;
 
717
null:
 
718
  null_value=1;
 
719
  return 0;
 
720
}
 
721
 
 
722
 
 
723
void Item_func_insert::fix_length_and_dec()
 
724
{
 
725
  ulonglong max_result_length;
 
726
 
 
727
  // Handle character set for args[0] and args[3].
 
728
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 3))
 
729
    return;
 
730
  max_result_length= ((ulonglong) args[0]->max_length+
 
731
                      (ulonglong) args[3]->max_length);
 
732
  if (max_result_length >= MAX_BLOB_WIDTH)
 
733
  {
 
734
    max_result_length= MAX_BLOB_WIDTH;
 
735
    maybe_null= 1;
 
736
  }
 
737
  max_length= (ulong) max_result_length;
 
738
}
 
739
 
 
740
 
 
741
String *Item_str_conv::val_str(String *str)
 
742
{
 
743
  DBUG_ASSERT(fixed == 1);
 
744
  String *res;
 
745
  if (!(res=args[0]->val_str(str)))
 
746
  {
 
747
    null_value=1; /* purecov: inspected */
 
748
    return 0; /* purecov: inspected */
 
749
  }
 
750
  null_value=0;
 
751
  if (multiply == 1)
 
752
  {
 
753
    uint len;
 
754
    res= copy_if_not_alloced(str,res,res->length());
 
755
    len= converter(collation.collation, (char*) res->ptr(), res->length(),
 
756
                                        (char*) res->ptr(), res->length());
 
757
    DBUG_ASSERT(len <= res->length());
 
758
    res->length(len);
 
759
  }
 
760
  else
 
761
  {
 
762
    uint len= res->length() * multiply;
 
763
    tmp_value.alloc(len);
 
764
    tmp_value.set_charset(collation.collation);
 
765
    len= converter(collation.collation, (char*) res->ptr(), res->length(),
 
766
                                        (char*) tmp_value.ptr(), len);
 
767
    tmp_value.length(len);
 
768
    res= &tmp_value;
 
769
  }
 
770
  return res;
 
771
}
 
772
 
 
773
 
 
774
void Item_func_lcase::fix_length_and_dec()
 
775
{
 
776
  collation.set(args[0]->collation);
 
777
  multiply= collation.collation->casedn_multiply;
 
778
  converter= collation.collation->cset->casedn;
 
779
  max_length= args[0]->max_length * multiply;
 
780
}
 
781
 
 
782
void Item_func_ucase::fix_length_and_dec()
 
783
{
 
784
  collation.set(args[0]->collation);
 
785
  multiply= collation.collation->caseup_multiply;
 
786
  converter= collation.collation->cset->caseup;
 
787
  max_length= args[0]->max_length * multiply;
 
788
}
 
789
 
 
790
 
 
791
String *Item_func_left::val_str(String *str)
 
792
{
 
793
  DBUG_ASSERT(fixed == 1);
 
794
  String *res= args[0]->val_str(str);
 
795
 
 
796
  /* must be longlong to avoid truncation */
 
797
  longlong length= args[1]->val_int();
 
798
  uint char_pos;
 
799
 
 
800
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
 
801
    return 0;
 
802
 
 
803
  /* if "unsigned_flag" is set, we have a *huge* positive number. */
 
804
  if ((length <= 0) && (!args[1]->unsigned_flag))
 
805
    return &my_empty_string;
 
806
 
 
807
  if ((res->length() <= (ulonglong) length) ||
 
808
      (res->length() <= (char_pos= res->charpos((int) length))))
 
809
    return res;
 
810
 
 
811
  tmp_value.set(*res, 0, char_pos);
 
812
  return &tmp_value;
 
813
}
 
814
 
 
815
 
 
816
void Item_str_func::left_right_max_length()
 
817
{
 
818
  max_length=args[0]->max_length;
 
819
  if (args[1]->const_item())
 
820
  {
 
821
    int length=(int) args[1]->val_int()*collation.collation->mbmaxlen;
 
822
    if (length <= 0)
 
823
      max_length=0;
 
824
    else
 
825
      set_if_smaller(max_length,(uint) length);
 
826
  }
 
827
}
 
828
 
 
829
 
 
830
void Item_func_left::fix_length_and_dec()
 
831
{
 
832
  collation.set(args[0]->collation);
 
833
  left_right_max_length();
 
834
}
 
835
 
 
836
 
 
837
String *Item_func_right::val_str(String *str)
 
838
{
 
839
  DBUG_ASSERT(fixed == 1);
 
840
  String *res= args[0]->val_str(str);
 
841
  /* must be longlong to avoid truncation */
 
842
  longlong length= args[1]->val_int();
 
843
 
 
844
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
 
845
    return 0; /* purecov: inspected */
 
846
 
 
847
  /* if "unsigned_flag" is set, we have a *huge* positive number. */
 
848
  if ((length <= 0) && (!args[1]->unsigned_flag))
 
849
    return &my_empty_string; /* purecov: inspected */
 
850
 
 
851
  if (res->length() <= (ulonglong) length)
 
852
    return res; /* purecov: inspected */
 
853
 
 
854
  uint start=res->numchars();
 
855
  if (start <= (uint) length)
 
856
    return res;
 
857
  start=res->charpos(start - (uint) length);
 
858
  tmp_value.set(*res,start,res->length()-start);
 
859
  return &tmp_value;
 
860
}
 
861
 
 
862
 
 
863
void Item_func_right::fix_length_and_dec()
 
864
{
 
865
  collation.set(args[0]->collation);
 
866
  left_right_max_length();
 
867
}
 
868
 
 
869
 
 
870
String *Item_func_substr::val_str(String *str)
 
871
{
 
872
  DBUG_ASSERT(fixed == 1);
 
873
  String *res  = args[0]->val_str(str);
 
874
  /* must be longlong to avoid truncation */
 
875
  longlong start= args[1]->val_int();
 
876
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
877
  /* Limit so that code sees out-of-bound value properly. */
 
878
  longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
 
879
  longlong tmp_length;
 
880
 
 
881
  if ((null_value=(args[0]->null_value || args[1]->null_value ||
 
882
                   (arg_count == 3 && args[2]->null_value))))
 
883
    return 0; /* purecov: inspected */
 
884
 
 
885
  /* Negative or zero length, will return empty string. */
 
886
  if ((arg_count == 3) && (length <= 0) && 
 
887
      (length == 0 || !args[2]->unsigned_flag))
 
888
    return &my_empty_string;
 
889
 
 
890
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
891
  /* Set here so that rest of code sees out-of-bound value as such. */
 
892
  if ((length <= 0) || (length > INT_MAX32))
 
893
    length= INT_MAX32;
 
894
 
 
895
  /* if "unsigned_flag" is set, we have a *huge* positive number. */
 
896
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
897
  if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
 
898
      (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
 
899
    return &my_empty_string;
 
900
 
 
901
  start= ((start < 0) ? res->numchars() + start : start - 1);
 
902
  start= res->charpos((int) start);
 
903
  if ((start < 0) || ((uint) start + 1 > res->length()))
 
904
    return &my_empty_string;
 
905
 
 
906
  length= res->charpos((int) length, (uint32) start);
 
907
  tmp_length= res->length() - start;
 
908
  length= min(length, tmp_length);
 
909
 
 
910
  if (!start && (longlong) res->length() == length)
 
911
    return res;
 
912
  tmp_value.set(*res, (uint32) start, (uint32) length);
 
913
  return &tmp_value;
 
914
}
 
915
 
 
916
 
 
917
void Item_func_substr::fix_length_and_dec()
 
918
{
 
919
  max_length=args[0]->max_length;
 
920
 
 
921
  collation.set(args[0]->collation);
 
922
  if (args[1]->const_item())
 
923
  {
 
924
    int32 start= (int32) args[1]->val_int();
 
925
    if (start < 0)
 
926
      max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start);
 
927
    else
 
928
      max_length-= min((uint)(start - 1), max_length);
 
929
  }
 
930
  if (arg_count == 3 && args[2]->const_item())
 
931
  {
 
932
    int32 length= (int32) args[2]->val_int();
 
933
    if (length <= 0)
 
934
      max_length=0; /* purecov: inspected */
 
935
    else
 
936
      set_if_smaller(max_length,(uint) length);
 
937
  }
 
938
  max_length*= collation.collation->mbmaxlen;
 
939
}
 
940
 
 
941
 
 
942
void Item_func_substr_index::fix_length_and_dec()
 
943
 
944
  max_length= args[0]->max_length;
 
945
 
 
946
  if (agg_arg_charsets(collation, args, 2, MY_COLL_CMP_CONV, 1))
 
947
    return;
 
948
}
 
949
 
 
950
 
 
951
String *Item_func_substr_index::val_str(String *str)
 
952
{
 
953
  DBUG_ASSERT(fixed == 1);
 
954
  String *res= args[0]->val_str(str);
 
955
  String *delimiter= args[1]->val_str(&tmp_value);
 
956
  int32 count= (int32) args[2]->val_int();
 
957
  uint offset;
 
958
 
 
959
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
 
960
  {                                     // string and/or delim are null
 
961
    null_value=1;
 
962
    return 0;
 
963
  }
 
964
  null_value=0;
 
965
  uint delimiter_length= delimiter->length();
 
966
  if (!res->length() || !delimiter_length || !count)
 
967
    return &my_empty_string;            // Wrong parameters
 
968
 
 
969
  res->set_charset(collation.collation);
 
970
 
 
971
#ifdef USE_MB
 
972
  if (use_mb(res->charset()))
 
973
  {
 
974
    const char *ptr= res->ptr();
 
975
    const char *strend= ptr+res->length();
 
976
    const char *end= strend-delimiter_length+1;
 
977
    const char *search= delimiter->ptr();
 
978
    const char *search_end= search+delimiter_length;
 
979
    int32 n=0,c=count,pass;
 
980
    register uint32 l;
 
981
    for (pass=(count>0);pass<2;++pass)
 
982
    {
 
983
      while (ptr < end)
 
984
      {
 
985
        if (*ptr == *search)
 
986
        {
 
987
          register char *i,*j;
 
988
          i=(char*) ptr+1; j=(char*) search+1;
 
989
          while (j != search_end)
 
990
            if (*i++ != *j++) goto skip;
 
991
          if (pass==0) ++n;
 
992
          else if (!--c) break;
 
993
          ptr+= delimiter_length;
 
994
          continue;
 
995
        }
 
996
    skip:
 
997
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
 
998
        else ++ptr;
 
999
      } /* either not found or got total number when count<0 */
 
1000
      if (pass == 0) /* count<0 */
 
1001
      {
 
1002
        c+=n+1;
 
1003
        if (c<=0) return res; /* not found, return original string */
 
1004
        ptr=res->ptr();
 
1005
      }
 
1006
      else
 
1007
      {
 
1008
        if (c) return res; /* Not found, return original string */
 
1009
        if (count>0) /* return left part */
 
1010
        {
 
1011
          tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
 
1012
        }
 
1013
        else /* return right part */
 
1014
        {
 
1015
          ptr+= delimiter_length;
 
1016
          tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
 
1017
        }
 
1018
      }
 
1019
    }
 
1020
  }
 
1021
  else
 
1022
#endif /* USE_MB */
 
1023
  {
 
1024
    if (count > 0)
 
1025
    {                                   // start counting from the beginning
 
1026
      for (offset=0; ; offset+= delimiter_length)
 
1027
      {
 
1028
        if ((int) (offset= res->strstr(*delimiter, offset)) < 0)
 
1029
          return res;                   // Didn't find, return org string
 
1030
        if (!--count)
 
1031
        {
 
1032
          tmp_value.set(*res,0,offset);
 
1033
          break;
 
1034
        }
 
1035
      }
 
1036
    }
 
1037
    else
 
1038
    {
 
1039
      /*
 
1040
        Negative index, start counting at the end
 
1041
      */
 
1042
      for (offset=res->length(); offset ;)
 
1043
      {
 
1044
        /* 
 
1045
          this call will result in finding the position pointing to one 
 
1046
          address space less than where the found substring is located
 
1047
          in res
 
1048
        */
 
1049
        if ((int) (offset= res->strrstr(*delimiter, offset)) < 0)
 
1050
          return res;                   // Didn't find, return org string
 
1051
        /*
 
1052
          At this point, we've searched for the substring
 
1053
          the number of times as supplied by the index value
 
1054
        */
 
1055
        if (!++count)
 
1056
        {
 
1057
          offset+= delimiter_length;
 
1058
          tmp_value.set(*res,offset,res->length()- offset);
 
1059
          break;
 
1060
        }
 
1061
      }
 
1062
    }
 
1063
  }
 
1064
  /*
 
1065
    We always mark tmp_value as const so that if val_str() is called again
 
1066
    on this object, we don't disrupt the contents of tmp_value when it was
 
1067
    derived from another String.
 
1068
  */
 
1069
  tmp_value.mark_as_const();
 
1070
  return (&tmp_value);
 
1071
}
 
1072
 
 
1073
/*
 
1074
** The trim functions are extension to ANSI SQL because they trim substrings
 
1075
** They ltrim() and rtrim() functions are optimized for 1 byte strings
 
1076
** They also return the original string if possible, else they return
 
1077
** a substring that points at the original string.
 
1078
*/
 
1079
 
 
1080
 
 
1081
String *Item_func_ltrim::val_str(String *str)
 
1082
{
 
1083
  DBUG_ASSERT(fixed == 1);
 
1084
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
 
1085
  String tmp(buff,sizeof(buff),system_charset_info);
 
1086
  String *res, *remove_str;
 
1087
  uint remove_length;
 
1088
 
 
1089
  res= args[0]->val_str(str);
 
1090
  if ((null_value=args[0]->null_value))
 
1091
    return 0;
 
1092
  remove_str= &remove;                          /* Default value. */
 
1093
  if (arg_count == 2)
 
1094
  {
 
1095
    remove_str= args[1]->val_str(&tmp);
 
1096
    if ((null_value= args[1]->null_value))
 
1097
      return 0;
 
1098
  }
 
1099
 
 
1100
  if ((remove_length= remove_str->length()) == 0 ||
 
1101
      remove_length > res->length())
 
1102
    return res;
 
1103
 
 
1104
  ptr= (char*) res->ptr();
 
1105
  end= ptr+res->length();
 
1106
  if (remove_length == 1)
 
1107
  {
 
1108
    char chr=(*remove_str)[0];
 
1109
    while (ptr != end && *ptr == chr)
 
1110
      ptr++;
 
1111
  }
 
1112
  else
 
1113
  {
 
1114
    const char *r_ptr=remove_str->ptr();
 
1115
    end-=remove_length;
 
1116
    while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
 
1117
      ptr+=remove_length;
 
1118
    end+=remove_length;
 
1119
  }
 
1120
  if (ptr == res->ptr())
 
1121
    return res;
 
1122
  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
 
1123
  return &tmp_value;
 
1124
}
 
1125
 
 
1126
 
 
1127
String *Item_func_rtrim::val_str(String *str)
 
1128
{
 
1129
  DBUG_ASSERT(fixed == 1);
 
1130
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
 
1131
  String tmp(buff, sizeof(buff), system_charset_info);
 
1132
  String *res, *remove_str;
 
1133
  uint remove_length;
 
1134
 
 
1135
  res= args[0]->val_str(str);
 
1136
  if ((null_value=args[0]->null_value))
 
1137
    return 0;
 
1138
  remove_str= &remove;                          /* Default value. */
 
1139
  if (arg_count == 2)
 
1140
  {
 
1141
    remove_str= args[1]->val_str(&tmp);
 
1142
    if ((null_value= args[1]->null_value))
 
1143
      return 0;
 
1144
  }
 
1145
 
 
1146
  if ((remove_length= remove_str->length()) == 0 ||
 
1147
      remove_length > res->length())
 
1148
    return res;
 
1149
 
 
1150
  ptr= (char*) res->ptr();
 
1151
  end= ptr+res->length();
 
1152
#ifdef USE_MB
 
1153
  char *p=ptr;
 
1154
  register uint32 l;
 
1155
#endif
 
1156
  if (remove_length == 1)
 
1157
  {
 
1158
    char chr=(*remove_str)[0];
 
1159
#ifdef USE_MB
 
1160
    if (use_mb(res->charset()))
 
1161
    {
 
1162
      while (ptr < end)
 
1163
      {
 
1164
        if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr;
 
1165
        else ++ptr;
 
1166
      }
 
1167
      ptr=p;
 
1168
    }
 
1169
#endif
 
1170
    while (ptr != end  && end[-1] == chr)
 
1171
      end--;
 
1172
  }
 
1173
  else
 
1174
  {
 
1175
    const char *r_ptr=remove_str->ptr();
 
1176
#ifdef USE_MB
 
1177
    if (use_mb(res->charset()))
 
1178
    {
 
1179
  loop:
 
1180
      while (ptr + remove_length < end)
 
1181
      {
 
1182
        if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
 
1183
        else ++ptr;
 
1184
      }
 
1185
      if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
 
1186
      {
 
1187
        end-=remove_length;
 
1188
        ptr=p;
 
1189
        goto loop;
 
1190
      }
 
1191
    }
 
1192
    else
 
1193
#endif /* USE_MB */
 
1194
    {
 
1195
      while (ptr + remove_length <= end &&
 
1196
             !memcmp(end-remove_length, r_ptr, remove_length))
 
1197
        end-=remove_length;
 
1198
    }
 
1199
  }
 
1200
  if (end == res->ptr()+res->length())
 
1201
    return res;
 
1202
  tmp_value.set(*res,0,(uint) (end-res->ptr()));
 
1203
  return &tmp_value;
 
1204
}
 
1205
 
 
1206
 
 
1207
String *Item_func_trim::val_str(String *str)
 
1208
{
 
1209
  DBUG_ASSERT(fixed == 1);
 
1210
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
 
1211
  const char *r_ptr;
 
1212
  String tmp(buff, sizeof(buff), system_charset_info);
 
1213
  String *res, *remove_str;
 
1214
  uint remove_length;
 
1215
 
 
1216
  res= args[0]->val_str(str);
 
1217
  if ((null_value=args[0]->null_value))
 
1218
    return 0;
 
1219
  remove_str= &remove;                          /* Default value. */
 
1220
  if (arg_count == 2)
 
1221
  {
 
1222
    remove_str= args[1]->val_str(&tmp);
 
1223
    if ((null_value= args[1]->null_value))
 
1224
      return 0;
 
1225
  }
 
1226
 
 
1227
  if ((remove_length= remove_str->length()) == 0 ||
 
1228
      remove_length > res->length())
 
1229
    return res;
 
1230
 
 
1231
  ptr= (char*) res->ptr();
 
1232
  end= ptr+res->length();
 
1233
  r_ptr= remove_str->ptr();
 
1234
  while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
 
1235
    ptr+=remove_length;
 
1236
#ifdef USE_MB
 
1237
  if (use_mb(res->charset()))
 
1238
  {
 
1239
    char *p=ptr;
 
1240
    register uint32 l;
 
1241
 loop:
 
1242
    while (ptr + remove_length < end)
 
1243
    {
 
1244
      if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
 
1245
      else ++ptr;
 
1246
    }
 
1247
    if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
 
1248
    {
 
1249
      end-=remove_length;
 
1250
      ptr=p;
 
1251
      goto loop;
 
1252
    }
 
1253
    ptr=p;
 
1254
  }
 
1255
  else
 
1256
#endif /* USE_MB */
 
1257
  {
 
1258
    while (ptr + remove_length <= end &&
 
1259
           !memcmp(end-remove_length,r_ptr,remove_length))
 
1260
      end-=remove_length;
 
1261
  }
 
1262
  if (ptr == res->ptr() && end == ptr+res->length())
 
1263
    return res;
 
1264
  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
 
1265
  return &tmp_value;
 
1266
}
 
1267
 
 
1268
void Item_func_trim::fix_length_and_dec()
 
1269
{
 
1270
  max_length= args[0]->max_length;
 
1271
  if (arg_count == 1)
 
1272
  {
 
1273
    collation.set(args[0]->collation);
 
1274
    remove.set_charset(collation.collation);
 
1275
    remove.set_ascii(" ",1);
 
1276
  }
 
1277
  else
 
1278
  {
 
1279
    // Handle character set for args[1] and args[0].
 
1280
    // Note that we pass args[1] as the first item, and args[0] as the second.
 
1281
    if (agg_arg_charsets(collation, &args[1], 2, MY_COLL_CMP_CONV, -1))
 
1282
      return;
 
1283
  }
 
1284
}
 
1285
 
 
1286
void Item_func_trim::print(String *str, enum_query_type query_type)
 
1287
{
 
1288
  if (arg_count == 1)
 
1289
  {
 
1290
    Item_func::print(str, query_type);
 
1291
    return;
 
1292
  }
 
1293
  str->append(Item_func_trim::func_name());
 
1294
  str->append('(');
 
1295
  str->append(mode_name());
 
1296
  str->append(' ');
 
1297
  args[1]->print(str, query_type);
 
1298
  str->append(STRING_WITH_LEN(" from "));
 
1299
  args[0]->print(str, query_type);
 
1300
  str->append(')');
 
1301
}
 
1302
 
 
1303
 
 
1304
/* Item_func_password */
 
1305
 
 
1306
String *Item_func_password::val_str(String *str)
 
1307
{
 
1308
  DBUG_ASSERT(fixed == 1);
 
1309
  String *res= args[0]->val_str(str); 
 
1310
  if ((null_value=args[0]->null_value))
 
1311
    return 0;
 
1312
  if (res->length() == 0)
 
1313
    return &my_empty_string;
 
1314
  make_scrambled_password(tmp_value, res->c_ptr());
 
1315
  str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, res->charset());
 
1316
  return str;
 
1317
}
 
1318
 
 
1319
char *Item_func_password::alloc(THD *thd, const char *password)
 
1320
{
 
1321
  char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH+1);
 
1322
  if (buff)
 
1323
    make_scrambled_password(buff, password);
 
1324
  return buff;
 
1325
}
 
1326
 
 
1327
/* Item_func_old_password */
 
1328
 
 
1329
String *Item_func_old_password::val_str(String *str)
 
1330
{
 
1331
  DBUG_ASSERT(fixed == 1);
 
1332
  String *res= args[0]->val_str(str);
 
1333
  if ((null_value=args[0]->null_value))
 
1334
    return 0;
 
1335
  if (res->length() == 0)
 
1336
    return &my_empty_string;
 
1337
  make_scrambled_password_323(tmp_value, res->c_ptr());
 
1338
  str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, res->charset());
 
1339
  return str;
 
1340
}
 
1341
 
 
1342
char *Item_func_old_password::alloc(THD *thd, const char *password)
 
1343
{
 
1344
  char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1);
 
1345
  if (buff)
 
1346
    make_scrambled_password_323(buff, password);
 
1347
  return buff;
 
1348
}
 
1349
 
 
1350
 
 
1351
#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
 
1352
 
 
1353
String *Item_func_encrypt::val_str(String *str)
 
1354
{
 
1355
  DBUG_ASSERT(fixed == 1);
 
1356
  String *res  =args[0]->val_str(str);
 
1357
 
 
1358
#ifdef HAVE_CRYPT
 
1359
  char salt[3],*salt_ptr;
 
1360
  if ((null_value=args[0]->null_value))
 
1361
    return 0;
 
1362
  if (res->length() == 0)
 
1363
    return &my_empty_string;
 
1364
 
 
1365
  if (arg_count == 1)
 
1366
  {                                     // generate random salt
 
1367
    time_t timestamp=current_thd->query_start();
 
1368
    salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
 
1369
    salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
 
1370
    salt[2] = 0;
 
1371
    salt_ptr=salt;
 
1372
  }
 
1373
  else
 
1374
  {                                     // obtain salt from the first two bytes
 
1375
    String *salt_str=args[1]->val_str(&tmp_value);
 
1376
    if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
 
1377
      return 0;
 
1378
    salt_ptr= salt_str->c_ptr();
 
1379
  }
 
1380
  pthread_mutex_lock(&LOCK_crypt);
 
1381
  char *tmp= crypt(res->c_ptr(),salt_ptr);
 
1382
  if (!tmp)
 
1383
  {
 
1384
    pthread_mutex_unlock(&LOCK_crypt);
 
1385
    null_value= 1;
 
1386
    return 0;
 
1387
  }
 
1388
  str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
 
1389
  str->copy();
 
1390
  pthread_mutex_unlock(&LOCK_crypt);
 
1391
  return str;
 
1392
#else
 
1393
  null_value=1;
 
1394
  return 0;
 
1395
#endif  /* HAVE_CRYPT */
 
1396
}
 
1397
 
 
1398
void Item_func_encode::fix_length_and_dec()
 
1399
{
 
1400
  max_length=args[0]->max_length;
 
1401
  maybe_null=args[0]->maybe_null || args[1]->maybe_null;
 
1402
  collation.set(&my_charset_bin);
 
1403
}
 
1404
 
 
1405
String *Item_func_encode::val_str(String *str)
 
1406
{
 
1407
  String *res;
 
1408
  char pw_buff[80];
 
1409
  String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
 
1410
  String *password;
 
1411
  DBUG_ASSERT(fixed == 1);
 
1412
 
 
1413
  if (!(res=args[0]->val_str(str)))
 
1414
  {
 
1415
    null_value=1; /* purecov: inspected */
 
1416
    return 0; /* purecov: inspected */
 
1417
  }
 
1418
 
 
1419
  if (!(password=args[1]->val_str(& tmp_pw_value)))
 
1420
  {
 
1421
    null_value=1;
 
1422
    return 0;
 
1423
  }
 
1424
 
 
1425
  null_value=0;
 
1426
  res=copy_if_not_alloced(str,res,res->length());
 
1427
  SQL_CRYPT sql_crypt(password->ptr());
 
1428
  sql_crypt.init();
 
1429
  sql_crypt.encode((char*) res->ptr(),res->length());
 
1430
  res->set_charset(&my_charset_bin);
 
1431
  return res;
 
1432
}
 
1433
 
 
1434
String *Item_func_decode::val_str(String *str)
 
1435
{
 
1436
  String *res;
 
1437
  char pw_buff[80];
 
1438
  String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
 
1439
  String *password;
 
1440
  DBUG_ASSERT(fixed == 1);
 
1441
 
 
1442
  if (!(res=args[0]->val_str(str)))
 
1443
  {
 
1444
    null_value=1; /* purecov: inspected */
 
1445
    return 0; /* purecov: inspected */
 
1446
  }
 
1447
 
 
1448
  if (!(password=args[1]->val_str(& tmp_pw_value)))
 
1449
  {
 
1450
    null_value=1;
 
1451
    return 0;
 
1452
  }
 
1453
 
 
1454
  null_value=0;
 
1455
  res=copy_if_not_alloced(str,res,res->length());
 
1456
  SQL_CRYPT sql_crypt(password->ptr());
 
1457
  sql_crypt.init();
 
1458
  sql_crypt.decode((char*) res->ptr(),res->length());
 
1459
  return res;
 
1460
}
 
1461
 
 
1462
 
 
1463
Item *Item_func_sysconst::safe_charset_converter(CHARSET_INFO *tocs)
 
1464
{
 
1465
  Item_string *conv;
 
1466
  uint conv_errors;
 
1467
  String tmp, cstr, *ostr= val_str(&tmp);
 
1468
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
 
1469
  if (conv_errors ||
 
1470
      !(conv= new Item_static_string_func(fully_qualified_func_name(),
 
1471
                                          cstr.ptr(), cstr.length(),
 
1472
                                          cstr.charset(),
 
1473
                                          collation.derivation)))
 
1474
  {
 
1475
    return NULL;
 
1476
  }
 
1477
  conv->str_value.copy();
 
1478
  conv->str_value.mark_as_const();
 
1479
  return conv;
 
1480
}
 
1481
 
 
1482
 
 
1483
String *Item_func_database::val_str(String *str)
 
1484
{
 
1485
  DBUG_ASSERT(fixed == 1);
 
1486
  THD *thd= current_thd;
 
1487
  if (thd->db == NULL)
 
1488
  {
 
1489
    null_value= 1;
 
1490
    return 0;
 
1491
  }
 
1492
  else
 
1493
    str->copy(thd->db, thd->db_length, system_charset_info);
 
1494
  return str;
 
1495
}
 
1496
 
 
1497
 
 
1498
/**
 
1499
  @todo
 
1500
  make USER() replicate properly (currently it is replicated to "")
 
1501
*/
 
1502
bool Item_func_user::init(const char *user, const char *host)
 
1503
{
 
1504
  DBUG_ASSERT(fixed == 1);
 
1505
 
 
1506
  // For system threads (e.g. replication SQL thread) user may be empty
 
1507
  if (user)
 
1508
  {
 
1509
    CHARSET_INFO *cs= str_value.charset();
 
1510
    uint res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
 
1511
 
 
1512
    if (str_value.alloc(res_length))
 
1513
    {
 
1514
      null_value=1;
 
1515
      return TRUE;
 
1516
    }
 
1517
 
 
1518
    res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), res_length,
 
1519
                                  "%s@%s", user, host);
 
1520
    str_value.length(res_length);
 
1521
    str_value.mark_as_const();
 
1522
  }
 
1523
  return FALSE;
 
1524
}
 
1525
 
 
1526
 
 
1527
bool Item_func_user::fix_fields(THD *thd, Item **ref)
 
1528
{
 
1529
  return (Item_func_sysconst::fix_fields(thd, ref) ||
 
1530
          init(thd->main_security_ctx.user,
 
1531
               thd->main_security_ctx.host_or_ip));
 
1532
}
 
1533
 
 
1534
 
 
1535
bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
 
1536
{
 
1537
  if (Item_func_sysconst::fix_fields(thd, ref))
 
1538
    return TRUE;
 
1539
 
 
1540
  Security_context *ctx=
 
1541
                         thd->security_ctx;
 
1542
  return init(ctx->priv_user, ctx->priv_host);
 
1543
}
 
1544
 
 
1545
 
 
1546
/**
 
1547
  Change a number to format '3,333,333,333.000'.
 
1548
 
 
1549
  This should be 'internationalized' sometimes.
 
1550
*/
 
1551
 
 
1552
const int FORMAT_MAX_DECIMALS= 30;
 
1553
 
 
1554
Item_func_format::Item_func_format(Item *org, Item *dec)
 
1555
: Item_str_func(org, dec)
 
1556
{
 
1557
}
 
1558
 
 
1559
void Item_func_format::fix_length_and_dec()
 
1560
{
 
1561
  collation.set(default_charset());
 
1562
  uint char_length= args[0]->max_length/args[0]->collation.collation->mbmaxlen;
 
1563
  max_length= ((char_length + (char_length-args[0]->decimals)/3) *
 
1564
               collation.collation->mbmaxlen);
 
1565
}
 
1566
 
 
1567
 
 
1568
/**
 
1569
  @todo
 
1570
  This needs to be fixed for multi-byte character set where numbers
 
1571
  are stored in more than one byte
 
1572
*/
 
1573
 
 
1574
String *Item_func_format::val_str(String *str)
 
1575
{
 
1576
  uint32 length;
 
1577
  uint32 str_length;
 
1578
  /* Number of decimal digits */
 
1579
  int dec;
 
1580
  /* Number of characters used to represent the decimals, including '.' */
 
1581
  uint32 dec_length;
 
1582
  int diff;
 
1583
  DBUG_ASSERT(fixed == 1);
 
1584
 
 
1585
  dec= (int) args[1]->val_int();
 
1586
  if (args[1]->null_value)
 
1587
  {
 
1588
    null_value=1;
 
1589
    return NULL;
 
1590
  }
 
1591
 
 
1592
  dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
 
1593
  dec_length= dec ? dec+1 : 0;
 
1594
  null_value=0;
 
1595
 
 
1596
  if (args[0]->result_type() == DECIMAL_RESULT ||
 
1597
      args[0]->result_type() == INT_RESULT)
 
1598
  {
 
1599
    my_decimal dec_val, rnd_dec, *res;
 
1600
    res= args[0]->val_decimal(&dec_val);
 
1601
    if ((null_value=args[0]->null_value))
 
1602
      return 0; /* purecov: inspected */
 
1603
    my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
 
1604
    my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
 
1605
    str_length= str->length();
 
1606
    if (rnd_dec.sign())
 
1607
      str_length--;
 
1608
  }
 
1609
  else
 
1610
  {
 
1611
    double nr= args[0]->val_real();
 
1612
    if ((null_value=args[0]->null_value))
 
1613
      return 0; /* purecov: inspected */
 
1614
    nr= my_double_round(nr, (longlong) dec, FALSE, FALSE);
 
1615
    /* Here default_charset() is right as this is not an automatic conversion */
 
1616
    str->set_real(nr, dec, default_charset());
 
1617
    if (isnan(nr))
 
1618
      return str;
 
1619
    str_length=str->length();
 
1620
    if (nr < 0)
 
1621
      str_length--;                             // Don't count sign
 
1622
  }
 
1623
  /* We need this test to handle 'nan' values */
 
1624
  if (str_length >= dec_length+4)
 
1625
  {
 
1626
    char *tmp,*pos;
 
1627
    length= str->length()+(diff=((int)(str_length- dec_length-1))/3);
 
1628
    str= copy_if_not_alloced(&tmp_str,str,length);
 
1629
    str->length(length);
 
1630
    tmp= (char*) str->ptr()+length - dec_length-1;
 
1631
    for (pos= (char*) str->ptr()+length-1; pos != tmp; pos--)
 
1632
      pos[0]= pos[-diff];
 
1633
    while (diff)
 
1634
    {
 
1635
      *pos= *(pos - diff);
 
1636
      pos--;
 
1637
      *pos= *(pos - diff);
 
1638
      pos--;
 
1639
      *pos= *(pos - diff);
 
1640
      pos--;
 
1641
      pos[0]=',';
 
1642
      pos--;
 
1643
      diff--;
 
1644
    }
 
1645
  }
 
1646
  return str;
 
1647
}
 
1648
 
 
1649
 
 
1650
void Item_func_format::print(String *str, enum_query_type query_type)
 
1651
{
 
1652
  str->append(STRING_WITH_LEN("format("));
 
1653
  args[0]->print(str, query_type);
 
1654
  str->append(',');
 
1655
  args[1]->print(str, query_type);
 
1656
  str->append(')');
 
1657
}
 
1658
 
 
1659
void Item_func_elt::fix_length_and_dec()
 
1660
{
 
1661
  max_length=0;
 
1662
  decimals=0;
 
1663
 
 
1664
  if (agg_arg_charsets(collation, args+1, arg_count-1, MY_COLL_ALLOW_CONV, 1))
 
1665
    return;
 
1666
 
 
1667
  for (uint i= 1 ; i < arg_count ; i++)
 
1668
  {
 
1669
    set_if_bigger(max_length,args[i]->max_length);
 
1670
    set_if_bigger(decimals,args[i]->decimals);
 
1671
  }
 
1672
  maybe_null=1;                                 // NULL if wrong first arg
 
1673
}
 
1674
 
 
1675
 
 
1676
double Item_func_elt::val_real()
 
1677
{
 
1678
  DBUG_ASSERT(fixed == 1);
 
1679
  uint tmp;
 
1680
  null_value=1;
 
1681
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
 
1682
    return 0.0;
 
1683
  double result= args[tmp]->val_real();
 
1684
  null_value= args[tmp]->null_value;
 
1685
  return result;
 
1686
}
 
1687
 
 
1688
 
 
1689
longlong Item_func_elt::val_int()
 
1690
{
 
1691
  DBUG_ASSERT(fixed == 1);
 
1692
  uint tmp;
 
1693
  null_value=1;
 
1694
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
 
1695
    return 0;
 
1696
 
 
1697
  longlong result= args[tmp]->val_int();
 
1698
  null_value= args[tmp]->null_value;
 
1699
  return result;
 
1700
}
 
1701
 
 
1702
 
 
1703
String *Item_func_elt::val_str(String *str)
 
1704
{
 
1705
  DBUG_ASSERT(fixed == 1);
 
1706
  uint tmp;
 
1707
  null_value=1;
 
1708
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
 
1709
    return NULL;
 
1710
 
 
1711
  String *result= args[tmp]->val_str(str);
 
1712
  if (result)
 
1713
    result->set_charset(collation.collation);
 
1714
  null_value= args[tmp]->null_value;
 
1715
  return result;
 
1716
}
 
1717
 
 
1718
 
 
1719
void Item_func_make_set::split_sum_func(THD *thd, Item **ref_pointer_array,
 
1720
                                        List<Item> &fields)
 
1721
{
 
1722
  item->split_sum_func2(thd, ref_pointer_array, fields, &item, TRUE);
 
1723
  Item_str_func::split_sum_func(thd, ref_pointer_array, fields);
 
1724
}
 
1725
 
 
1726
 
 
1727
void Item_func_make_set::fix_length_and_dec()
 
1728
{
 
1729
  max_length=arg_count-1;
 
1730
 
 
1731
  if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
 
1732
    return;
 
1733
  
 
1734
  for (uint i=0 ; i < arg_count ; i++)
 
1735
    max_length+=args[i]->max_length;
 
1736
 
 
1737
  used_tables_cache|=     item->used_tables();
 
1738
  not_null_tables_cache&= item->not_null_tables();
 
1739
  const_item_cache&=      item->const_item();
 
1740
  with_sum_func= with_sum_func || item->with_sum_func;
 
1741
}
 
1742
 
 
1743
 
 
1744
void Item_func_make_set::update_used_tables()
 
1745
{
 
1746
  Item_func::update_used_tables();
 
1747
  item->update_used_tables();
 
1748
  used_tables_cache|=item->used_tables();
 
1749
  const_item_cache&=item->const_item();
 
1750
}
 
1751
 
 
1752
 
 
1753
String *Item_func_make_set::val_str(String *str)
 
1754
{
 
1755
  DBUG_ASSERT(fixed == 1);
 
1756
  ulonglong bits;
 
1757
  bool first_found=0;
 
1758
  Item **ptr=args;
 
1759
  String *result=&my_empty_string;
 
1760
 
 
1761
  bits=item->val_int();
 
1762
  if ((null_value=item->null_value))
 
1763
    return NULL;
 
1764
 
 
1765
  if (arg_count < 64)
 
1766
    bits &= ((ulonglong) 1 << arg_count)-1;
 
1767
 
 
1768
  for (; bits; bits >>= 1, ptr++)
 
1769
  {
 
1770
    if (bits & 1)
 
1771
    {
 
1772
      String *res= (*ptr)->val_str(str);
 
1773
      if (res)                                  // Skip nulls
 
1774
      {
 
1775
        if (!first_found)
 
1776
        {                                       // First argument
 
1777
          first_found=1;
 
1778
          if (res != str)
 
1779
            result=res;                         // Use original string
 
1780
          else
 
1781
          {
 
1782
            if (tmp_str.copy(*res))             // Don't use 'str'
 
1783
              return &my_empty_string;
 
1784
            result= &tmp_str;
 
1785
          }
 
1786
        }
 
1787
        else
 
1788
        {
 
1789
          if (result != &tmp_str)
 
1790
          {                                     // Copy data to tmp_str
 
1791
            if (tmp_str.alloc(result->length()+res->length()+1) ||
 
1792
                tmp_str.copy(*result))
 
1793
              return &my_empty_string;
 
1794
            result= &tmp_str;
 
1795
          }
 
1796
          if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
 
1797
            return &my_empty_string;
 
1798
        }
 
1799
      }
 
1800
    }
 
1801
  }
 
1802
  return result;
 
1803
}
 
1804
 
 
1805
 
 
1806
Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg)
 
1807
{
 
1808
  Item *new_item= item->transform(transformer, arg);
 
1809
  if (!new_item)
 
1810
    return 0;
 
1811
 
 
1812
  /*
 
1813
    THD::change_item_tree() should be called only if the tree was
 
1814
    really transformed, i.e. when a new item has been created.
 
1815
    Otherwise we'll be allocating a lot of unnecessary memory for
 
1816
    change records at each execution.
 
1817
  */
 
1818
  if (item != new_item)
 
1819
    current_thd->change_item_tree(&item, new_item);
 
1820
  return Item_str_func::transform(transformer, arg);
 
1821
}
 
1822
 
 
1823
 
 
1824
void Item_func_make_set::print(String *str, enum_query_type query_type)
 
1825
{
 
1826
  str->append(STRING_WITH_LEN("make_set("));
 
1827
  item->print(str, query_type);
 
1828
  if (arg_count)
 
1829
  {
 
1830
    str->append(',');
 
1831
    print_args(str, 0, query_type);
 
1832
  }
 
1833
  str->append(')');
 
1834
}
 
1835
 
 
1836
 
 
1837
String *Item_func_char::val_str(String *str)
 
1838
{
 
1839
  DBUG_ASSERT(fixed == 1);
 
1840
  str->length(0);
 
1841
  str->set_charset(collation.collation);
 
1842
  for (uint i=0 ; i < arg_count ; i++)
 
1843
  {
 
1844
    int32 num=(int32) args[i]->val_int();
 
1845
    if (!args[i]->null_value)
 
1846
    {
 
1847
      char char_num= (char) num;
 
1848
      if (num&0xFF000000L) {
 
1849
        str->append((char)(num>>24));
 
1850
        goto b2;
 
1851
      } else if (num&0xFF0000L) {
 
1852
    b2:        str->append((char)(num>>16));
 
1853
        goto b1;
 
1854
      } else if (num&0xFF00L) {
 
1855
    b1:        str->append((char)(num>>8));
 
1856
      }
 
1857
      str->append(&char_num, 1);
 
1858
    }
 
1859
  }
 
1860
  str->realloc(str->length());                  // Add end 0 (for Purify)
 
1861
  return check_well_formed_result(str);
 
1862
}
 
1863
 
 
1864
 
 
1865
inline String* alloc_buffer(String *res,String *str,String *tmp_value,
 
1866
                            ulong length)
 
1867
{
 
1868
  if (res->alloced_length() < length)
 
1869
  {
 
1870
    if (str->alloced_length() >= length)
 
1871
    {
 
1872
      (void) str->copy(*res);
 
1873
      str->length(length);
 
1874
      return str;
 
1875
    }
 
1876
    if (tmp_value->alloc(length))
 
1877
      return 0;
 
1878
    (void) tmp_value->copy(*res);
 
1879
    tmp_value->length(length);
 
1880
    return tmp_value;
 
1881
  }
 
1882
  res->length(length);
 
1883
  return res;
 
1884
}
 
1885
 
 
1886
 
 
1887
void Item_func_repeat::fix_length_and_dec()
 
1888
{
 
1889
  collation.set(args[0]->collation);
 
1890
  if (args[1]->const_item())
 
1891
  {
 
1892
    /* must be longlong to avoid truncation */
 
1893
    longlong count= args[1]->val_int();
 
1894
 
 
1895
    /* Assumes that the maximum length of a String is < INT_MAX32. */
 
1896
    /* Set here so that rest of code sees out-of-bound value as such. */
 
1897
    if (count > INT_MAX32)
 
1898
      count= INT_MAX32;
 
1899
 
 
1900
    ulonglong max_result_length= (ulonglong) args[0]->max_length * count;
 
1901
    if (max_result_length >= MAX_BLOB_WIDTH)
 
1902
    {
 
1903
      max_result_length= MAX_BLOB_WIDTH;
 
1904
      maybe_null= 1;
 
1905
    }
 
1906
    max_length= (ulong) max_result_length;
 
1907
  }
 
1908
  else
 
1909
  {
 
1910
    max_length= MAX_BLOB_WIDTH;
 
1911
    maybe_null= 1;
 
1912
  }
 
1913
}
 
1914
 
 
1915
/**
 
1916
  Item_func_repeat::str is carefully written to avoid reallocs
 
1917
  as much as possible at the cost of a local buffer
 
1918
*/
 
1919
 
 
1920
String *Item_func_repeat::val_str(String *str)
 
1921
{
 
1922
  DBUG_ASSERT(fixed == 1);
 
1923
  uint length,tot_length;
 
1924
  char *to;
 
1925
  /* must be longlong to avoid truncation */
 
1926
  longlong count= args[1]->val_int();
 
1927
  String *res= args[0]->val_str(str);
 
1928
 
 
1929
  if (args[0]->null_value || args[1]->null_value)
 
1930
    goto err;                           // string and/or delim are null
 
1931
  null_value= 0;
 
1932
 
 
1933
  if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
 
1934
    return &my_empty_string;
 
1935
 
 
1936
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
1937
  /* Bounds check on count:  If this is triggered, we will error. */
 
1938
  if ((ulonglong) count > INT_MAX32)
 
1939
    count= INT_MAX32;
 
1940
  if (count == 1)                       // To avoid reallocs
 
1941
    return res;
 
1942
  length=res->length();
 
1943
  // Safe length check
 
1944
  if (length > current_thd->variables.max_allowed_packet / (uint) count)
 
1945
  {
 
1946
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
1947
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
1948
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
1949
                        func_name(), current_thd->variables.max_allowed_packet);
 
1950
    goto err;
 
1951
  }
 
1952
  tot_length= length*(uint) count;
 
1953
  if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
 
1954
    goto err;
 
1955
 
 
1956
  to=(char*) res->ptr()+length;
 
1957
  while (--count)
 
1958
  {
 
1959
    memcpy(to,res->ptr(),length);
 
1960
    to+=length;
 
1961
  }
 
1962
  return (res);
 
1963
 
 
1964
err:
 
1965
  null_value=1;
 
1966
  return 0;
 
1967
}
 
1968
 
 
1969
 
 
1970
void Item_func_rpad::fix_length_and_dec()
 
1971
{
 
1972
  // Handle character set for args[0] and args[2].
 
1973
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
 
1974
    return;
 
1975
  if (args[1]->const_item())
 
1976
  {
 
1977
    ulonglong length= 0;
 
1978
 
 
1979
    if (collation.collation->mbmaxlen > 0)
 
1980
    {
 
1981
      ulonglong temp= (ulonglong) args[1]->val_int();
 
1982
 
 
1983
      /* Assumes that the maximum length of a String is < INT_MAX32. */
 
1984
      /* Set here so that rest of code sees out-of-bound value as such. */
 
1985
      if (temp > INT_MAX32)
 
1986
        temp = INT_MAX32;
 
1987
 
 
1988
      length= temp * collation.collation->mbmaxlen;
 
1989
    }
 
1990
 
 
1991
    if (length >= MAX_BLOB_WIDTH)
 
1992
    {
 
1993
      length= MAX_BLOB_WIDTH;
 
1994
      maybe_null= 1;
 
1995
    }
 
1996
    max_length= (ulong) length;
 
1997
  }
 
1998
  else
 
1999
  {
 
2000
    max_length= MAX_BLOB_WIDTH;
 
2001
    maybe_null= 1;
 
2002
  }
 
2003
}
 
2004
 
 
2005
 
 
2006
String *Item_func_rpad::val_str(String *str)
 
2007
{
 
2008
  DBUG_ASSERT(fixed == 1);
 
2009
  uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
 
2010
  char *to;
 
2011
  const char *ptr_pad;
 
2012
  /* must be longlong to avoid truncation */
 
2013
  longlong count= args[1]->val_int();
 
2014
  longlong byte_count;
 
2015
  String *res= args[0]->val_str(str);
 
2016
  String *rpad= args[2]->val_str(&rpad_str);
 
2017
 
 
2018
  if (!res || args[1]->null_value || !rpad || 
 
2019
      ((count < 0) && !args[1]->unsigned_flag))
 
2020
    goto err;
 
2021
  null_value=0;
 
2022
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
2023
  /* Set here so that rest of code sees out-of-bound value as such. */
 
2024
  if ((ulonglong) count > INT_MAX32)
 
2025
    count= INT_MAX32;
 
2026
  if (count <= (res_char_length= res->numchars()))
 
2027
  {                                             // String to pad is big enough
 
2028
    res->length(res->charpos((int) count));     // Shorten result if longer
 
2029
    return (res);
 
2030
  }
 
2031
  pad_char_length= rpad->numchars();
 
2032
 
 
2033
  byte_count= count * collation.collation->mbmaxlen;
 
2034
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
 
2035
  {
 
2036
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2037
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
2038
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
2039
                        func_name(), current_thd->variables.max_allowed_packet);
 
2040
    goto err;
 
2041
  }
 
2042
  if (args[2]->null_value || !pad_char_length)
 
2043
    goto err;
 
2044
  res_byte_length= res->length();       /* Must be done before alloc_buffer */
 
2045
  if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
 
2046
    goto err;
 
2047
 
 
2048
  to= (char*) res->ptr()+res_byte_length;
 
2049
  ptr_pad=rpad->ptr();
 
2050
  pad_byte_length= rpad->length();
 
2051
  count-= res_char_length;
 
2052
  for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
 
2053
  {
 
2054
    memcpy(to,ptr_pad,pad_byte_length);
 
2055
    to+= pad_byte_length;
 
2056
  }
 
2057
  if (count)
 
2058
  {
 
2059
    pad_byte_length= rpad->charpos((int) count);
 
2060
    memcpy(to,ptr_pad,(size_t) pad_byte_length);
 
2061
    to+= pad_byte_length;
 
2062
  }
 
2063
  res->length(to- (char*) res->ptr());
 
2064
  return (res);
 
2065
 
 
2066
 err:
 
2067
  null_value=1;
 
2068
  return 0;
 
2069
}
 
2070
 
 
2071
 
 
2072
void Item_func_lpad::fix_length_and_dec()
 
2073
{
 
2074
  // Handle character set for args[0] and args[2].
 
2075
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
 
2076
    return;
 
2077
  
 
2078
  if (args[1]->const_item())
 
2079
  {
 
2080
    ulonglong length= 0;
 
2081
 
 
2082
    if (collation.collation->mbmaxlen > 0)
 
2083
    {
 
2084
      ulonglong temp= (ulonglong) args[1]->val_int();
 
2085
 
 
2086
      /* Assumes that the maximum length of a String is < INT_MAX32. */
 
2087
      /* Set here so that rest of code sees out-of-bound value as such. */
 
2088
      if (temp > INT_MAX32)
 
2089
        temp= INT_MAX32;
 
2090
 
 
2091
      length= temp * collation.collation->mbmaxlen;
 
2092
    }
 
2093
 
 
2094
    if (length >= MAX_BLOB_WIDTH)
 
2095
    {
 
2096
      length= MAX_BLOB_WIDTH;
 
2097
      maybe_null= 1;
 
2098
    }
 
2099
    max_length= (ulong) length;
 
2100
  }
 
2101
  else
 
2102
  {
 
2103
    max_length= MAX_BLOB_WIDTH;
 
2104
    maybe_null= 1;
 
2105
  }
 
2106
}
 
2107
 
 
2108
 
 
2109
String *Item_func_lpad::val_str(String *str)
 
2110
{
 
2111
  DBUG_ASSERT(fixed == 1);
 
2112
  uint32 res_char_length,pad_char_length;
 
2113
  /* must be longlong to avoid truncation */
 
2114
  longlong count= args[1]->val_int();
 
2115
  longlong byte_count;
 
2116
  String *res= args[0]->val_str(&tmp_value);
 
2117
  String *pad= args[2]->val_str(&lpad_str);
 
2118
 
 
2119
  if (!res || args[1]->null_value || !pad ||  
 
2120
      ((count < 0) && !args[1]->unsigned_flag))
 
2121
    goto err;  
 
2122
  null_value=0;
 
2123
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
2124
  /* Set here so that rest of code sees out-of-bound value as such. */
 
2125
  if ((ulonglong) count > INT_MAX32)
 
2126
    count= INT_MAX32;
 
2127
 
 
2128
  res_char_length= res->numchars();
 
2129
 
 
2130
  if (count <= res_char_length)
 
2131
  {
 
2132
    res->length(res->charpos((int) count));
 
2133
    return res;
 
2134
  }
 
2135
  
 
2136
  pad_char_length= pad->numchars();
 
2137
  byte_count= count * collation.collation->mbmaxlen;
 
2138
  
 
2139
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
 
2140
  {
 
2141
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2142
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
2143
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
2144
                        func_name(), current_thd->variables.max_allowed_packet);
 
2145
    goto err;
 
2146
  }
 
2147
 
 
2148
  if (args[2]->null_value || !pad_char_length ||
 
2149
      str->alloc((uint32) byte_count))
 
2150
    goto err;
 
2151
  
 
2152
  str->length(0);
 
2153
  str->set_charset(collation.collation);
 
2154
  count-= res_char_length;
 
2155
  while (count >= pad_char_length)
 
2156
  {
 
2157
    str->append(*pad);
 
2158
    count-= pad_char_length;
 
2159
  }
 
2160
  if (count > 0)
 
2161
    str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
 
2162
 
 
2163
  str->append(*res);
 
2164
  null_value= 0;
 
2165
  return str;
 
2166
 
 
2167
err:
 
2168
  null_value= 1;
 
2169
  return 0;
 
2170
}
 
2171
 
 
2172
 
 
2173
String *Item_func_conv::val_str(String *str)
 
2174
{
 
2175
  DBUG_ASSERT(fixed == 1);
 
2176
  String *res= args[0]->val_str(str);
 
2177
  char *endptr,ans[65],*ptr;
 
2178
  longlong dec;
 
2179
  int from_base= (int) args[1]->val_int();
 
2180
  int to_base= (int) args[2]->val_int();
 
2181
  int err;
 
2182
 
 
2183
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
 
2184
      abs(to_base) > 36 || abs(to_base) < 2 ||
 
2185
      abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
 
2186
  {
 
2187
    null_value= 1;
 
2188
    return NULL;
 
2189
  }
 
2190
  null_value= 0;
 
2191
  unsigned_flag= !(from_base < 0);
 
2192
 
 
2193
  if (args[0]->field_type() == MYSQL_TYPE_BIT) 
 
2194
  {
 
2195
    /* 
 
2196
     Special case: The string representation of BIT doesn't resemble the
 
2197
     decimal representation, so we shouldn't change it to string and then to
 
2198
     decimal. 
 
2199
    */
 
2200
    dec= args[0]->val_int();
 
2201
  }
 
2202
  else
 
2203
  {
 
2204
    if (from_base < 0)
 
2205
      dec= my_strntoll(res->charset(), res->ptr(), res->length(),
 
2206
                       -from_base, &endptr, &err);
 
2207
    else
 
2208
      dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
 
2209
                                   from_base, &endptr, &err);
 
2210
  }
 
2211
 
 
2212
  ptr= longlong2str(dec, ans, to_base);
 
2213
  if (str->copy(ans, (uint32) (ptr-ans), default_charset()))
 
2214
    return &my_empty_string;
 
2215
  return str;
 
2216
}
 
2217
 
 
2218
 
 
2219
String *Item_func_conv_charset::val_str(String *str)
 
2220
{
 
2221
  DBUG_ASSERT(fixed == 1);
 
2222
  if (use_cached_value)
 
2223
    return null_value ? 0 : &str_value;
 
2224
  String *arg= args[0]->val_str(str);
 
2225
  uint dummy_errors;
 
2226
  if (!arg)
 
2227
  {
 
2228
    null_value=1;
 
2229
    return 0;
 
2230
  }
 
2231
  null_value= str_value.copy(arg->ptr(),arg->length(),arg->charset(),
 
2232
                             conv_charset, &dummy_errors);
 
2233
  return null_value ? 0 : check_well_formed_result(&str_value);
 
2234
}
 
2235
 
 
2236
void Item_func_conv_charset::fix_length_and_dec()
 
2237
{
 
2238
  collation.set(conv_charset, DERIVATION_IMPLICIT);
 
2239
  max_length = args[0]->max_length*conv_charset->mbmaxlen;
 
2240
}
 
2241
 
 
2242
void Item_func_conv_charset::print(String *str, enum_query_type query_type)
 
2243
{
 
2244
  str->append(STRING_WITH_LEN("convert("));
 
2245
  args[0]->print(str, query_type);
 
2246
  str->append(STRING_WITH_LEN(" using "));
 
2247
  str->append(conv_charset->csname);
 
2248
  str->append(')');
 
2249
}
 
2250
 
 
2251
String *Item_func_set_collation::val_str(String *str)
 
2252
{
 
2253
  DBUG_ASSERT(fixed == 1);
 
2254
  str=args[0]->val_str(str);
 
2255
  if ((null_value=args[0]->null_value))
 
2256
    return 0;
 
2257
  str->set_charset(collation.collation);
 
2258
  return str;
 
2259
}
 
2260
 
 
2261
void Item_func_set_collation::fix_length_and_dec()
 
2262
{
 
2263
  CHARSET_INFO *set_collation;
 
2264
  const char *colname;
 
2265
  String tmp, *str= args[1]->val_str(&tmp);
 
2266
  colname= str->c_ptr();
 
2267
  if (colname == binary_keyword)
 
2268
    set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
 
2269
                                         MY_CS_BINSORT,MYF(0));
 
2270
  else
 
2271
  {
 
2272
    if (!(set_collation= get_charset_by_name(colname,MYF(0))))
 
2273
    {
 
2274
      my_error(ER_UNKNOWN_COLLATION, MYF(0), colname);
 
2275
      return;
 
2276
    }
 
2277
  }
 
2278
 
 
2279
  if (!set_collation || 
 
2280
      !my_charset_same(args[0]->collation.collation,set_collation))
 
2281
  {
 
2282
    my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
 
2283
             colname, args[0]->collation.collation->csname);
 
2284
    return;
 
2285
  }
 
2286
  collation.set(set_collation, DERIVATION_EXPLICIT,
 
2287
                args[0]->collation.repertoire);
 
2288
  max_length= args[0]->max_length;
 
2289
}
 
2290
 
 
2291
 
 
2292
bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
 
2293
{
 
2294
  /* Assume we don't have rtti */
 
2295
  if (this == item)
 
2296
    return 1;
 
2297
  if (item->type() != FUNC_ITEM)
 
2298
    return 0;
 
2299
  Item_func *item_func=(Item_func*) item;
 
2300
  if (arg_count != item_func->arg_count ||
 
2301
      functype() != item_func->functype())
 
2302
    return 0;
 
2303
  Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
 
2304
  if (collation.collation != item_func_sc->collation.collation)
 
2305
    return 0;
 
2306
  for (uint i=0; i < arg_count ; i++)
 
2307
    if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
 
2308
      return 0;
 
2309
  return 1;
 
2310
}
 
2311
 
 
2312
 
 
2313
void Item_func_set_collation::print(String *str, enum_query_type query_type)
 
2314
{
 
2315
  str->append('(');
 
2316
  args[0]->print(str, query_type);
 
2317
  str->append(STRING_WITH_LEN(" collate "));
 
2318
  DBUG_ASSERT(args[1]->basic_const_item() &&
 
2319
              args[1]->type() == Item::STRING_ITEM);
 
2320
  args[1]->str_value.print(str);
 
2321
  str->append(')');
 
2322
}
 
2323
 
 
2324
String *Item_func_charset::val_str(String *str)
 
2325
{
 
2326
  DBUG_ASSERT(fixed == 1);
 
2327
  uint dummy_errors;
 
2328
 
 
2329
  CHARSET_INFO *cs= args[0]->collation.collation; 
 
2330
  null_value= 0;
 
2331
  str->copy(cs->csname, strlen(cs->csname),
 
2332
            &my_charset_latin1, collation.collation, &dummy_errors);
 
2333
  return str;
 
2334
}
 
2335
 
 
2336
String *Item_func_collation::val_str(String *str)
 
2337
{
 
2338
  DBUG_ASSERT(fixed == 1);
 
2339
  uint dummy_errors;
 
2340
  CHARSET_INFO *cs= args[0]->collation.collation; 
 
2341
 
 
2342
  null_value= 0;
 
2343
  str->copy(cs->name, strlen(cs->name),
 
2344
            &my_charset_latin1, collation.collation, &dummy_errors);
 
2345
  return str;
 
2346
}
 
2347
 
 
2348
 
 
2349
void Item_func_weight_string::fix_length_and_dec()
 
2350
{
 
2351
  CHARSET_INFO *cs= args[0]->collation.collation;
 
2352
  collation.set(&my_charset_bin, args[0]->collation.derivation);
 
2353
  flags= my_strxfrm_flag_normalize(flags, cs->levels_for_order);
 
2354
  max_length= cs->mbmaxlen * max(args[0]->max_length, nweights);
 
2355
  maybe_null= 1;
 
2356
}
 
2357
 
 
2358
 
 
2359
/* Return a weight_string according to collation */
 
2360
String *Item_func_weight_string::val_str(String *str)
 
2361
{
 
2362
  String *res;
 
2363
  CHARSET_INFO *cs= args[0]->collation.collation;
 
2364
  uint tmp_length, frm_length;
 
2365
  DBUG_ASSERT(fixed == 1);
 
2366
 
 
2367
  if (args[0]->result_type() != STRING_RESULT ||
 
2368
      !(res= args[0]->val_str(str)))
 
2369
    goto nl;
 
2370
  
 
2371
  tmp_length= cs->coll->strnxfrmlen(cs, cs->mbmaxlen *
 
2372
                                        max(res->length(), nweights));
 
2373
 
 
2374
  if (tmp_value.alloc(tmp_length))
 
2375
    goto nl;
 
2376
 
 
2377
  frm_length= cs->coll->strnxfrm(cs,
 
2378
                                 (uchar*) tmp_value.ptr(), tmp_length,
 
2379
                                 nweights ? nweights : tmp_length,
 
2380
                                 (const uchar*) res->ptr(), res->length(),
 
2381
                                 flags);
 
2382
  tmp_value.length(frm_length);
 
2383
  null_value= 0;
 
2384
  return &tmp_value;
 
2385
 
 
2386
nl:
 
2387
  null_value= 1;
 
2388
  return 0;
 
2389
}
 
2390
 
 
2391
 
 
2392
String *Item_func_hex::val_str(String *str)
 
2393
{
 
2394
  String *res;
 
2395
  DBUG_ASSERT(fixed == 1);
 
2396
  if (args[0]->result_type() != STRING_RESULT)
 
2397
  {
 
2398
    ulonglong dec;
 
2399
    char ans[65],*ptr;
 
2400
    /* Return hex of unsigned longlong value */
 
2401
    if (args[0]->result_type() == REAL_RESULT ||
 
2402
        args[0]->result_type() == DECIMAL_RESULT)
 
2403
    {
 
2404
      double val= args[0]->val_real();
 
2405
      if ((val <= (double) LONGLONG_MIN) || 
 
2406
          (val >= (double) (ulonglong) ULONGLONG_MAX))
 
2407
        dec=  ~(longlong) 0;
 
2408
      else
 
2409
        dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
 
2410
    }
 
2411
    else
 
2412
      dec= (ulonglong) args[0]->val_int();
 
2413
 
 
2414
    if ((null_value= args[0]->null_value))
 
2415
      return 0;
 
2416
    ptr= longlong2str(dec,ans,16);
 
2417
    if (str->copy(ans,(uint32) (ptr-ans),default_charset()))
 
2418
      return &my_empty_string;                  // End of memory
 
2419
    return str;
 
2420
  }
 
2421
 
 
2422
  /* Convert given string to a hex string, character by character */
 
2423
  res= args[0]->val_str(str);
 
2424
  if (!res || tmp_value.alloc(res->length()*2+1))
 
2425
  {
 
2426
    null_value=1;
 
2427
    return 0;
 
2428
  }
 
2429
  null_value=0;
 
2430
  tmp_value.length(res->length()*2);
 
2431
 
 
2432
  octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
 
2433
  return &tmp_value;
 
2434
}
 
2435
 
 
2436
  /** Convert given hex string to a binary string. */
 
2437
 
 
2438
String *Item_func_unhex::val_str(String *str)
 
2439
{
 
2440
  const char *from, *end;
 
2441
  char *to;
 
2442
  String *res;
 
2443
  uint length;
 
2444
  DBUG_ASSERT(fixed == 1);
 
2445
 
 
2446
  res= args[0]->val_str(str);
 
2447
  if (!res || tmp_value.alloc(length= (1+res->length())/2))
 
2448
  {
 
2449
    null_value=1;
 
2450
    return 0;
 
2451
  }
 
2452
 
 
2453
  from= res->ptr();
 
2454
  null_value= 0;
 
2455
  tmp_value.length(length);
 
2456
  to= (char*) tmp_value.ptr();
 
2457
  if (res->length() % 2)
 
2458
  {
 
2459
    int hex_char;
 
2460
    *to++= hex_char= hexchar_to_int(*from++);
 
2461
    if ((null_value= (hex_char == -1)))
 
2462
      return 0;
 
2463
  }
 
2464
  for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
 
2465
  {
 
2466
    int hex_char;
 
2467
    *to= (hex_char= hexchar_to_int(from[0])) << 4;
 
2468
    if ((null_value= (hex_char == -1)))
 
2469
      return 0;
 
2470
    *to|= hex_char= hexchar_to_int(from[1]);
 
2471
    if ((null_value= (hex_char == -1)))
 
2472
      return 0;
 
2473
  }
 
2474
  return &tmp_value;
 
2475
}
 
2476
 
 
2477
 
 
2478
void Item_func_binary::print(String *str, enum_query_type query_type)
 
2479
{
 
2480
  str->append(STRING_WITH_LEN("cast("));
 
2481
  args[0]->print(str, query_type);
 
2482
  str->append(STRING_WITH_LEN(" as binary)"));
 
2483
}
 
2484
 
 
2485
 
 
2486
#include <my_dir.h>                             // For my_stat
 
2487
 
 
2488
String *Item_load_file::val_str(String *str)
 
2489
{
 
2490
  DBUG_ASSERT(fixed == 1);
 
2491
  String *file_name;
 
2492
  File file;
 
2493
  MY_STAT stat_info;
 
2494
  char path[FN_REFLEN];
 
2495
  DBUG_ENTER("load_file");
 
2496
 
 
2497
  if (!(file_name= args[0]->val_str(str)))
 
2498
    goto err;
 
2499
 
 
2500
  (void) fn_format(path, file_name->c_ptr(), mysql_real_data_home, "",
 
2501
                   MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
 
2502
 
 
2503
  /* Read only allowed from within dir specified by secure_file_priv */
 
2504
  if (opt_secure_file_priv &&
 
2505
      strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv)))
 
2506
    goto err;
 
2507
 
 
2508
  if (!my_stat(path, &stat_info, MYF(0)))
 
2509
    goto err;
 
2510
 
 
2511
  if (!(stat_info.st_mode & S_IROTH))
 
2512
  {
 
2513
    /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
 
2514
    goto err;
 
2515
  }
 
2516
  if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
 
2517
  {
 
2518
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2519
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
2520
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
2521
                        func_name(), current_thd->variables.max_allowed_packet);
 
2522
    goto err;
 
2523
  }
 
2524
  if (tmp_value.alloc(stat_info.st_size))
 
2525
    goto err;
 
2526
  if ((file = my_open(file_name->c_ptr(), O_RDONLY, MYF(0))) < 0)
 
2527
    goto err;
 
2528
  if (my_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size, MYF(MY_NABP)))
 
2529
  {
 
2530
    my_close(file, MYF(0));
 
2531
    goto err;
 
2532
  }
 
2533
  tmp_value.length(stat_info.st_size);
 
2534
  my_close(file, MYF(0));
 
2535
  null_value = 0;
 
2536
  DBUG_RETURN(&tmp_value);
 
2537
 
 
2538
err:
 
2539
  null_value = 1;
 
2540
  DBUG_RETURN(0);
 
2541
}
 
2542
 
 
2543
 
 
2544
String* Item_func_export_set::val_str(String* str)
 
2545
{
 
2546
  DBUG_ASSERT(fixed == 1);
 
2547
  ulonglong the_set = (ulonglong) args[0]->val_int();
 
2548
  String yes_buf, *yes;
 
2549
  yes = args[1]->val_str(&yes_buf);
 
2550
  String no_buf, *no;
 
2551
  no = args[2]->val_str(&no_buf);
 
2552
  String *sep = NULL, sep_buf ;
 
2553
 
 
2554
  uint num_set_values = 64;
 
2555
  ulonglong mask = 0x1;
 
2556
  str->length(0);
 
2557
  str->set_charset(collation.collation);
 
2558
 
 
2559
  /* Check if some argument is a NULL value */
 
2560
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
 
2561
  {
 
2562
    null_value=1;
 
2563
    return 0;
 
2564
  }
 
2565
  /*
 
2566
    Arg count can only be 3, 4 or 5 here. This is guaranteed from the
 
2567
    grammar for EXPORT_SET()
 
2568
  */
 
2569
  switch(arg_count) {
 
2570
  case 5:
 
2571
    num_set_values = (uint) args[4]->val_int();
 
2572
    if (num_set_values > 64)
 
2573
      num_set_values=64;
 
2574
    if (args[4]->null_value)
 
2575
    {
 
2576
      null_value=1;
 
2577
      return 0;
 
2578
    }
 
2579
    /* Fall through */
 
2580
  case 4:
 
2581
    if (!(sep = args[3]->val_str(&sep_buf)))    // Only true if NULL
 
2582
    {
 
2583
      null_value=1;
 
2584
      return 0;
 
2585
    }
 
2586
    break;
 
2587
  case 3:
 
2588
    {
 
2589
      /* errors is not checked - assume "," can always be converted */
 
2590
      uint errors;
 
2591
      sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin, collation.collation, &errors);
 
2592
      sep = &sep_buf;
 
2593
    }
 
2594
    break;
 
2595
  default:
 
2596
    DBUG_ASSERT(0); // cannot happen
 
2597
  }
 
2598
  null_value=0;
 
2599
 
 
2600
  for (uint i = 0; i < num_set_values; i++, mask = (mask << 1))
 
2601
  {
 
2602
    if (the_set & mask)
 
2603
      str->append(*yes);
 
2604
    else
 
2605
      str->append(*no);
 
2606
    if (i != num_set_values - 1)
 
2607
      str->append(*sep);
 
2608
  }
 
2609
  return str;
 
2610
}
 
2611
 
 
2612
void Item_func_export_set::fix_length_and_dec()
 
2613
{
 
2614
  uint length=max(args[1]->max_length,args[2]->max_length);
 
2615
  uint sep_length=(arg_count > 3 ? args[3]->max_length : 1);
 
2616
  max_length=length*64+sep_length*63;
 
2617
 
 
2618
  if (agg_arg_charsets(collation, args+1, min(4,arg_count)-1,
 
2619
                       MY_COLL_ALLOW_CONV, 1))
 
2620
    return;
 
2621
}
 
2622
 
 
2623
 
 
2624
#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))
 
2625
 
 
2626
/**
 
2627
  QUOTE() function returns argument string in single quotes suitable for
 
2628
  using in a SQL statement.
 
2629
 
 
2630
  Adds a \\ before all characters that needs to be escaped in a SQL string.
 
2631
  We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
 
2632
  running commands from a file in windows.
 
2633
 
 
2634
  This function is very useful when you want to generate SQL statements.
 
2635
 
 
2636
  @note
 
2637
    QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).
 
2638
 
 
2639
  @retval
 
2640
    str    Quoted string
 
2641
  @retval
 
2642
    NULL           Out of memory.
 
2643
*/
 
2644
 
 
2645
String *Item_func_quote::val_str(String *str)
 
2646
{
 
2647
  DBUG_ASSERT(fixed == 1);
 
2648
  /*
 
2649
    Bit mask that has 1 for set for the position of the following characters:
 
2650
    0, \, ' and ^Z
 
2651
  */
 
2652
 
 
2653
  static uchar escmask[32]=
 
2654
  {
 
2655
    0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
 
2656
    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
 
2657
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
 
2658
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
 
2659
  };
 
2660
 
 
2661
  char *from, *to, *end, *start;
 
2662
  String *arg= args[0]->val_str(str);
 
2663
  uint arg_length, new_length;
 
2664
  if (!arg)                                     // Null argument
 
2665
  {
 
2666
    /* Return the string 'NULL' */
 
2667
    str->copy(STRING_WITH_LEN("NULL"), collation.collation);
 
2668
    null_value= 0;
 
2669
    return str;
 
2670
  }
 
2671
 
 
2672
  arg_length= arg->length();
 
2673
  new_length= arg_length+2; /* for beginning and ending ' signs */
 
2674
 
 
2675
  for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
 
2676
    new_length+= get_esc_bit(escmask, (uchar) *from);
 
2677
 
 
2678
  if (tmp_value.alloc(new_length))
 
2679
    goto null;
 
2680
 
 
2681
  /*
 
2682
    We replace characters from the end to the beginning
 
2683
  */
 
2684
  to= (char*) tmp_value.ptr() + new_length - 1;
 
2685
  *to--= '\'';
 
2686
  for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
 
2687
  {
 
2688
    /*
 
2689
      We can't use the bitmask here as we want to replace \O and ^Z with 0
 
2690
      and Z
 
2691
    */
 
2692
    switch (*end)  {
 
2693
    case 0:
 
2694
      *to--= '0';
 
2695
      *to=   '\\';
 
2696
      break;
 
2697
    case '\032':
 
2698
      *to--= 'Z';
 
2699
      *to=   '\\';
 
2700
      break;
 
2701
    case '\'':
 
2702
    case '\\':
 
2703
      *to--= *end;
 
2704
      *to=   '\\';
 
2705
      break;
 
2706
    default:
 
2707
      *to= *end;
 
2708
      break;
 
2709
    }
 
2710
  }
 
2711
  *to= '\'';
 
2712
  tmp_value.length(new_length);
 
2713
  tmp_value.set_charset(collation.collation);
 
2714
  null_value= 0;
 
2715
  return &tmp_value;
 
2716
 
 
2717
null:
 
2718
  null_value= 1;
 
2719
  return 0;
 
2720
}
 
2721
 
 
2722
longlong Item_func_uncompressed_length::val_int()
 
2723
{
 
2724
  DBUG_ASSERT(fixed == 1);
 
2725
  String *res= args[0]->val_str(&value);
 
2726
  if (!res)
 
2727
  {
 
2728
    null_value=1;
 
2729
    return 0; /* purecov: inspected */
 
2730
  }
 
2731
  null_value=0;
 
2732
  if (res->is_empty()) return 0;
 
2733
 
 
2734
  /*
 
2735
    res->ptr() using is safe because we have tested that string is not empty,
 
2736
    res->c_ptr() is not used because:
 
2737
      - we do not need \0 terminated string to get first 4 bytes
 
2738
      - c_ptr() tests simbol after string end (uninitialiozed memory) which
 
2739
        confuse valgrind
 
2740
  */
 
2741
  return uint4korr(res->ptr()) & 0x3FFFFFFF;
 
2742
}
 
2743
 
 
2744
longlong Item_func_crc32::val_int()
 
2745
{
 
2746
  DBUG_ASSERT(fixed == 1);
 
2747
  String *res=args[0]->val_str(&value);
 
2748
  if (!res)
 
2749
  {
 
2750
    null_value=1;
 
2751
    return 0; /* purecov: inspected */
 
2752
  }
 
2753
  null_value=0;
 
2754
  return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
 
2755
}
 
2756
 
 
2757
#ifdef HAVE_COMPRESS
 
2758
#include "zlib.h"
 
2759
 
 
2760
String *Item_func_compress::val_str(String *str)
 
2761
{
 
2762
  int err= Z_OK, code;
 
2763
  ulong new_size;
 
2764
  String *res;
 
2765
  Byte *body;
 
2766
  char *tmp, *last_char;
 
2767
  DBUG_ASSERT(fixed == 1);
 
2768
 
 
2769
  if (!(res= args[0]->val_str(str)))
 
2770
  {
 
2771
    null_value= 1;
 
2772
    return 0;
 
2773
  }
 
2774
  null_value= 0;
 
2775
  if (res->is_empty()) return res;
 
2776
 
 
2777
  /*
 
2778
    Citation from zlib.h (comment for compress function):
 
2779
 
 
2780
    Compresses the source buffer into the destination buffer.  sourceLen is
 
2781
    the byte length of the source buffer. Upon entry, destLen is the total
 
2782
    size of the destination buffer, which must be at least 0.1% larger than
 
2783
    sourceLen plus 12 bytes.
 
2784
    We assume here that the buffer can't grow more than .25 %.
 
2785
  */
 
2786
  new_size= res->length() + res->length() / 5 + 12;
 
2787
 
 
2788
  // Check new_size overflow: new_size <= res->length()
 
2789
  if (((uint32) (new_size+5) <= res->length()) || 
 
2790
      buffer.realloc((uint32) new_size + 4 + 1))
 
2791
  {
 
2792
    null_value= 1;
 
2793
    return 0;
 
2794
  }
 
2795
 
 
2796
  body= ((Byte*)buffer.ptr()) + 4;
 
2797
 
 
2798
  // As far as we have checked res->is_empty() we can use ptr()
 
2799
  if ((err= compress(body, &new_size,
 
2800
                     (const Bytef*)res->ptr(), res->length())) != Z_OK)
 
2801
  {
 
2802
    code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
 
2803
    push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
 
2804
    null_value= 1;
 
2805
    return 0;
 
2806
  }
 
2807
 
 
2808
  tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
 
2809
  int4store(tmp, res->length() & 0x3FFFFFFF);
 
2810
 
 
2811
  /* This is to ensure that things works for CHAR fields, which trim ' ': */
 
2812
  last_char= ((char*)body)+new_size-1;
 
2813
  if (*last_char == ' ')
 
2814
  {
 
2815
    *++last_char= '.';
 
2816
    new_size++;
 
2817
  }
 
2818
 
 
2819
  buffer.length((uint32)new_size + 4);
 
2820
  return &buffer;
 
2821
}
 
2822
 
 
2823
 
 
2824
String *Item_func_uncompress::val_str(String *str)
 
2825
{
 
2826
  DBUG_ASSERT(fixed == 1);
 
2827
  String *res= args[0]->val_str(str);
 
2828
  ulong new_size;
 
2829
  int err;
 
2830
  uint code;
 
2831
 
 
2832
  if (!res)
 
2833
    goto err;
 
2834
  null_value= 0;
 
2835
  if (res->is_empty())
 
2836
    return res;
 
2837
 
 
2838
  /* If length is less than 4 bytes, data is corrupt */
 
2839
  if (res->length() <= 4)
 
2840
  {
 
2841
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
 
2842
                        ER_ZLIB_Z_DATA_ERROR,
 
2843
                        ER(ER_ZLIB_Z_DATA_ERROR));
 
2844
    goto err;
 
2845
  }
 
2846
 
 
2847
  /* Size of uncompressed data is stored as first 4 bytes of field */
 
2848
  new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
 
2849
  if (new_size > current_thd->variables.max_allowed_packet)
 
2850
  {
 
2851
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
 
2852
                        ER_TOO_BIG_FOR_UNCOMPRESS,
 
2853
                        ER(ER_TOO_BIG_FOR_UNCOMPRESS),
 
2854
                        current_thd->variables.max_allowed_packet);
 
2855
    goto err;
 
2856
  }
 
2857
  if (buffer.realloc((uint32)new_size))
 
2858
    goto err;
 
2859
 
 
2860
  if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
 
2861
                       ((const Bytef*)res->ptr())+4,res->length())) == Z_OK)
 
2862
  {
 
2863
    buffer.length((uint32) new_size);
 
2864
    return &buffer;
 
2865
  }
 
2866
 
 
2867
  code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
 
2868
         ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
 
2869
  push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
 
2870
 
 
2871
err:
 
2872
  null_value= 1;
 
2873
  return 0;
 
2874
}
 
2875
#endif
 
2876
 
 
2877
/*
 
2878
  UUID, as in
 
2879
    DCE 1.1: Remote Procedure Call,
 
2880
    Open Group Technical Standard Document Number C706, October 1997,
 
2881
    (supersedes C309 DCE: Remote Procedure Call 8/1994,
 
2882
    which was basis for ISO/IEC 11578:1996 specification)
 
2883
*/
 
2884
 
 
2885
static struct rand_struct uuid_rand;
 
2886
static uint nanoseq;
 
2887
static ulonglong uuid_time=0;
 
2888
static char clock_seq_and_node_str[]="-0000-000000000000";
 
2889
 
 
2890
/**
 
2891
  number of 100-nanosecond intervals between
 
2892
  1582-10-15 00:00:00.00 and 1970-01-01 00:00:00.00.
 
2893
*/
 
2894
#define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * 1000 * 10 )
 
2895
 
 
2896
#define UUID_VERSION      0x1000
 
2897
#define UUID_VARIANT      0x8000
 
2898
 
 
2899
static void tohex(char *to, uint from, uint len)
 
2900
{
 
2901
  to+= len;
 
2902
  while (len--)
 
2903
  {
 
2904
    *--to= _dig_vec_lower[from & 15];
 
2905
    from >>= 4;
 
2906
  }
 
2907
}
 
2908
 
 
2909
static void set_clock_seq_str()
 
2910
{
 
2911
  uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT;
 
2912
  tohex(clock_seq_and_node_str+1, clock_seq, 4);
 
2913
  nanoseq= 0;
 
2914
}
 
2915
 
 
2916
String *Item_func_uuid::val_str(String *str)
 
2917
{
 
2918
  DBUG_ASSERT(fixed == 1);
 
2919
  char *s;
 
2920
  THD *thd= current_thd;
 
2921
 
 
2922
  pthread_mutex_lock(&LOCK_uuid_generator);
 
2923
  if (! uuid_time) /* first UUID() call. initializing data */
 
2924
  {
 
2925
    ulong tmp=sql_rnd_with_mutex();
 
2926
    uchar mac[6];
 
2927
    int i;
 
2928
    if (my_gethwaddr(mac))
 
2929
    {
 
2930
      /* purecov: begin inspected */
 
2931
      /*
 
2932
        generating random "hardware addr"
 
2933
        and because specs explicitly specify that it should NOT correlate
 
2934
        with a clock_seq value (initialized random below), we use a separate
 
2935
        randominit() here
 
2936
      */
 
2937
      randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)global_query_id);
 
2938
      for (i=0; i < (int)sizeof(mac); i++)
 
2939
        mac[i]=(uchar)(my_rnd(&uuid_rand)*255);
 
2940
      /* purecov: end */    
 
2941
    }
 
2942
    s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1;
 
2943
    for (i=sizeof(mac)-1 ; i>=0 ; i--)
 
2944
    {
 
2945
      *--s=_dig_vec_lower[mac[i] & 15];
 
2946
      *--s=_dig_vec_lower[mac[i] >> 4];
 
2947
    }
 
2948
    randominit(&uuid_rand, tmp + (ulong) server_start_time,
 
2949
               tmp + (ulong) thd->status_var.bytes_sent);
 
2950
    set_clock_seq_str();
 
2951
  }
 
2952
 
 
2953
  ulonglong tv=my_getsystime() + UUID_TIME_OFFSET + nanoseq;
 
2954
  if (unlikely(tv < uuid_time))
 
2955
    set_clock_seq_str();
 
2956
  else if (unlikely(tv == uuid_time))
 
2957
  {
 
2958
    /* special protection from low-res system clocks */
 
2959
    nanoseq++;
 
2960
    tv++;
 
2961
  }
 
2962
  else
 
2963
  {
 
2964
    if (nanoseq)
 
2965
    {
 
2966
      tv-=nanoseq;
 
2967
      nanoseq=0;
 
2968
    }
 
2969
    DBUG_ASSERT(tv > uuid_time);
 
2970
  }
 
2971
  uuid_time=tv;
 
2972
  pthread_mutex_unlock(&LOCK_uuid_generator);
 
2973
 
 
2974
  uint32 time_low=            (uint32) (tv & 0xFFFFFFFF);
 
2975
  uint16 time_mid=            (uint16) ((tv >> 32) & 0xFFFF);
 
2976
  uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION);
 
2977
 
 
2978
  str->realloc(UUID_LENGTH+1);
 
2979
  str->length(UUID_LENGTH);
 
2980
  str->set_charset(system_charset_info);
 
2981
  s=(char *) str->ptr();
 
2982
  s[8]=s[13]='-';
 
2983
  tohex(s, time_low, 8);
 
2984
  tohex(s+9, time_mid, 4);
 
2985
  tohex(s+14, time_hi_and_version, 4);
 
2986
  strmov(s+18, clock_seq_and_node_str);
 
2987
  return str;
 
2988
}