~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/item_strfunc.cc

Removed/replaced DBUG symbols and TRUE/FALSE

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
  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
  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
  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
  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
  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
  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
  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
  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
  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
  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
    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
  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
  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
  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
  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
  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
  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
  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
  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
#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
 
1328
 
 
1329
String *Item_func_encrypt::val_str(String *str)
 
1330
{
 
1331
  assert(fixed == 1);
 
1332
  String *res  =args[0]->val_str(str);
 
1333
 
 
1334
#ifdef HAVE_CRYPT
 
1335
  char salt[3],*salt_ptr;
 
1336
  if ((null_value=args[0]->null_value))
 
1337
    return 0;
 
1338
  if (res->length() == 0)
 
1339
    return &my_empty_string;
 
1340
 
 
1341
  if (arg_count == 1)
 
1342
  {                                     // generate random salt
 
1343
    time_t timestamp=current_thd->query_start();
 
1344
    salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
 
1345
    salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
 
1346
    salt[2] = 0;
 
1347
    salt_ptr=salt;
 
1348
  }
 
1349
  else
 
1350
  {                                     // obtain salt from the first two bytes
 
1351
    String *salt_str=args[1]->val_str(&tmp_value);
 
1352
    if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
 
1353
      return 0;
 
1354
    salt_ptr= salt_str->c_ptr();
 
1355
  }
 
1356
  pthread_mutex_lock(&LOCK_crypt);
 
1357
  char *tmp= crypt(res->c_ptr(),salt_ptr);
 
1358
  if (!tmp)
 
1359
  {
 
1360
    pthread_mutex_unlock(&LOCK_crypt);
 
1361
    null_value= 1;
 
1362
    return 0;
 
1363
  }
 
1364
  str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
 
1365
  str->copy();
 
1366
  pthread_mutex_unlock(&LOCK_crypt);
 
1367
  return str;
 
1368
#else
 
1369
  null_value=1;
 
1370
  return 0;
 
1371
#endif  /* HAVE_CRYPT */
 
1372
}
 
1373
 
 
1374
void Item_func_encode::fix_length_and_dec()
 
1375
{
 
1376
  max_length=args[0]->max_length;
 
1377
  maybe_null=args[0]->maybe_null || args[1]->maybe_null;
 
1378
  collation.set(&my_charset_bin);
 
1379
}
 
1380
 
 
1381
String *Item_func_encode::val_str(String *str)
 
1382
{
 
1383
  String *res;
 
1384
  char pw_buff[80];
 
1385
  String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
 
1386
  String *password;
 
1387
  assert(fixed == 1);
 
1388
 
 
1389
  if (!(res=args[0]->val_str(str)))
 
1390
  {
 
1391
    null_value=1; /* purecov: inspected */
 
1392
    return 0; /* purecov: inspected */
 
1393
  }
 
1394
 
 
1395
  if (!(password=args[1]->val_str(& tmp_pw_value)))
 
1396
  {
 
1397
    null_value=1;
 
1398
    return 0;
 
1399
  }
 
1400
 
 
1401
  null_value=0;
 
1402
  res=copy_if_not_alloced(str,res,res->length());
 
1403
  SQL_CRYPT sql_crypt(password->ptr());
 
1404
  sql_crypt.init();
 
1405
  sql_crypt.encode((char*) res->ptr(),res->length());
 
1406
  res->set_charset(&my_charset_bin);
 
1407
  return res;
 
1408
}
 
1409
 
 
1410
String *Item_func_decode::val_str(String *str)
 
1411
{
 
1412
  String *res;
 
1413
  char pw_buff[80];
 
1414
  String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
 
1415
  String *password;
 
1416
  assert(fixed == 1);
 
1417
 
 
1418
  if (!(res=args[0]->val_str(str)))
 
1419
  {
 
1420
    null_value=1; /* purecov: inspected */
 
1421
    return 0; /* purecov: inspected */
 
1422
  }
 
1423
 
 
1424
  if (!(password=args[1]->val_str(& tmp_pw_value)))
 
1425
  {
 
1426
    null_value=1;
 
1427
    return 0;
 
1428
  }
 
1429
 
 
1430
  null_value=0;
 
1431
  res=copy_if_not_alloced(str,res,res->length());
 
1432
  SQL_CRYPT sql_crypt(password->ptr());
 
1433
  sql_crypt.init();
 
1434
  sql_crypt.decode((char*) res->ptr(),res->length());
 
1435
  return res;
 
1436
}
 
1437
 
 
1438
 
 
1439
Item *Item_func_sysconst::safe_charset_converter(CHARSET_INFO *tocs)
 
1440
{
 
1441
  Item_string *conv;
 
1442
  uint conv_errors;
 
1443
  String tmp, cstr, *ostr= val_str(&tmp);
 
1444
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
 
1445
  if (conv_errors ||
 
1446
      !(conv= new Item_static_string_func(fully_qualified_func_name(),
 
1447
                                          cstr.ptr(), cstr.length(),
 
1448
                                          cstr.charset(),
 
1449
                                          collation.derivation)))
 
1450
  {
 
1451
    return NULL;
 
1452
  }
 
1453
  conv->str_value.copy();
 
1454
  conv->str_value.mark_as_const();
 
1455
  return conv;
 
1456
}
 
1457
 
 
1458
 
 
1459
String *Item_func_database::val_str(String *str)
 
1460
{
 
1461
  assert(fixed == 1);
 
1462
  THD *thd= current_thd;
 
1463
  if (thd->db == NULL)
 
1464
  {
 
1465
    null_value= 1;
 
1466
    return 0;
 
1467
  }
 
1468
  else
 
1469
    str->copy(thd->db, thd->db_length, system_charset_info);
 
1470
  return str;
 
1471
}
 
1472
 
 
1473
 
 
1474
/**
 
1475
  @todo
 
1476
  make USER() replicate properly (currently it is replicated to "")
 
1477
*/
 
1478
bool Item_func_user::init(const char *user, const char *host)
 
1479
{
 
1480
  assert(fixed == 1);
 
1481
 
 
1482
  // For system threads (e.g. replication SQL thread) user may be empty
 
1483
  if (user)
 
1484
  {
 
1485
    CHARSET_INFO *cs= str_value.charset();
 
1486
    uint res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
 
1487
 
 
1488
    if (str_value.alloc(res_length))
 
1489
    {
 
1490
      null_value=1;
 
1491
      return true;
 
1492
    }
 
1493
 
 
1494
    res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), res_length,
 
1495
                                  "%s@%s", user, host);
 
1496
    str_value.length(res_length);
 
1497
    str_value.mark_as_const();
 
1498
  }
 
1499
  return false;
 
1500
}
 
1501
 
 
1502
 
 
1503
bool Item_func_user::fix_fields(THD *thd, Item **ref)
 
1504
{
 
1505
  return (Item_func_sysconst::fix_fields(thd, ref) ||
 
1506
          init(thd->main_security_ctx.user,
 
1507
               thd->main_security_ctx.host_or_ip));
 
1508
}
 
1509
 
 
1510
 
 
1511
bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
 
1512
{
 
1513
  if (Item_func_sysconst::fix_fields(thd, ref))
 
1514
    return true;
 
1515
 
 
1516
  Security_context *ctx=
 
1517
                         thd->security_ctx;
 
1518
  return init(ctx->priv_user, ctx->priv_host);
 
1519
}
 
1520
 
 
1521
 
 
1522
/**
 
1523
  Change a number to format '3,333,333,333.000'.
 
1524
 
 
1525
  This should be 'internationalized' sometimes.
 
1526
*/
 
1527
 
 
1528
const int FORMAT_MAX_DECIMALS= 30;
 
1529
 
 
1530
Item_func_format::Item_func_format(Item *org, Item *dec)
 
1531
: Item_str_func(org, dec)
 
1532
{
 
1533
}
 
1534
 
 
1535
void Item_func_format::fix_length_and_dec()
 
1536
{
 
1537
  collation.set(default_charset());
 
1538
  uint char_length= args[0]->max_length/args[0]->collation.collation->mbmaxlen;
 
1539
  max_length= ((char_length + (char_length-args[0]->decimals)/3) *
 
1540
               collation.collation->mbmaxlen);
 
1541
}
 
1542
 
 
1543
 
 
1544
/**
 
1545
  @todo
 
1546
  This needs to be fixed for multi-byte character set where numbers
 
1547
  are stored in more than one byte
 
1548
*/
 
1549
 
 
1550
String *Item_func_format::val_str(String *str)
 
1551
{
 
1552
  uint32 length;
 
1553
  uint32 str_length;
 
1554
  /* Number of decimal digits */
 
1555
  int dec;
 
1556
  /* Number of characters used to represent the decimals, including '.' */
 
1557
  uint32 dec_length;
 
1558
  int diff;
 
1559
  assert(fixed == 1);
 
1560
 
 
1561
  dec= (int) args[1]->val_int();
 
1562
  if (args[1]->null_value)
 
1563
  {
 
1564
    null_value=1;
 
1565
    return NULL;
 
1566
  }
 
1567
 
 
1568
  dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
 
1569
  dec_length= dec ? dec+1 : 0;
 
1570
  null_value=0;
 
1571
 
 
1572
  if (args[0]->result_type() == DECIMAL_RESULT ||
 
1573
      args[0]->result_type() == INT_RESULT)
 
1574
  {
 
1575
    my_decimal dec_val, rnd_dec, *res;
 
1576
    res= args[0]->val_decimal(&dec_val);
 
1577
    if ((null_value=args[0]->null_value))
 
1578
      return 0; /* purecov: inspected */
 
1579
    my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
 
1580
    my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
 
1581
    str_length= str->length();
 
1582
    if (rnd_dec.sign())
 
1583
      str_length--;
 
1584
  }
 
1585
  else
 
1586
  {
 
1587
    double nr= args[0]->val_real();
 
1588
    if ((null_value=args[0]->null_value))
 
1589
      return 0; /* purecov: inspected */
 
1590
    nr= my_double_round(nr, (longlong) dec, false, false);
 
1591
    /* Here default_charset() is right as this is not an automatic conversion */
 
1592
    str->set_real(nr, dec, default_charset());
 
1593
    if (isnan(nr))
 
1594
      return str;
 
1595
    str_length=str->length();
 
1596
    if (nr < 0)
 
1597
      str_length--;                             // Don't count sign
 
1598
  }
 
1599
  /* We need this test to handle 'nan' values */
 
1600
  if (str_length >= dec_length+4)
 
1601
  {
 
1602
    char *tmp,*pos;
 
1603
    length= str->length()+(diff=((int)(str_length- dec_length-1))/3);
 
1604
    str= copy_if_not_alloced(&tmp_str,str,length);
 
1605
    str->length(length);
 
1606
    tmp= (char*) str->ptr()+length - dec_length-1;
 
1607
    for (pos= (char*) str->ptr()+length-1; pos != tmp; pos--)
 
1608
      pos[0]= pos[-diff];
 
1609
    while (diff)
 
1610
    {
 
1611
      *pos= *(pos - diff);
 
1612
      pos--;
 
1613
      *pos= *(pos - diff);
 
1614
      pos--;
 
1615
      *pos= *(pos - diff);
 
1616
      pos--;
 
1617
      pos[0]=',';
 
1618
      pos--;
 
1619
      diff--;
 
1620
    }
 
1621
  }
 
1622
  return str;
 
1623
}
 
1624
 
 
1625
 
 
1626
void Item_func_format::print(String *str, enum_query_type query_type)
 
1627
{
 
1628
  str->append(STRING_WITH_LEN("format("));
 
1629
  args[0]->print(str, query_type);
 
1630
  str->append(',');
 
1631
  args[1]->print(str, query_type);
 
1632
  str->append(')');
 
1633
}
 
1634
 
 
1635
void Item_func_elt::fix_length_and_dec()
 
1636
{
 
1637
  max_length=0;
 
1638
  decimals=0;
 
1639
 
 
1640
  if (agg_arg_charsets(collation, args+1, arg_count-1, MY_COLL_ALLOW_CONV, 1))
 
1641
    return;
 
1642
 
 
1643
  for (uint i= 1 ; i < arg_count ; i++)
 
1644
  {
 
1645
    set_if_bigger(max_length,args[i]->max_length);
 
1646
    set_if_bigger(decimals,args[i]->decimals);
 
1647
  }
 
1648
  maybe_null=1;                                 // NULL if wrong first arg
 
1649
}
 
1650
 
 
1651
 
 
1652
double Item_func_elt::val_real()
 
1653
{
 
1654
  assert(fixed == 1);
 
1655
  uint tmp;
 
1656
  null_value=1;
 
1657
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
 
1658
    return 0.0;
 
1659
  double result= args[tmp]->val_real();
 
1660
  null_value= args[tmp]->null_value;
 
1661
  return result;
 
1662
}
 
1663
 
 
1664
 
 
1665
longlong Item_func_elt::val_int()
 
1666
{
 
1667
  assert(fixed == 1);
 
1668
  uint tmp;
 
1669
  null_value=1;
 
1670
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
 
1671
    return 0;
 
1672
 
 
1673
  longlong result= args[tmp]->val_int();
 
1674
  null_value= args[tmp]->null_value;
 
1675
  return result;
 
1676
}
 
1677
 
 
1678
 
 
1679
String *Item_func_elt::val_str(String *str)
 
1680
{
 
1681
  assert(fixed == 1);
 
1682
  uint tmp;
 
1683
  null_value=1;
 
1684
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
 
1685
    return NULL;
 
1686
 
 
1687
  String *result= args[tmp]->val_str(str);
 
1688
  if (result)
 
1689
    result->set_charset(collation.collation);
 
1690
  null_value= args[tmp]->null_value;
 
1691
  return result;
 
1692
}
 
1693
 
 
1694
 
 
1695
void Item_func_make_set::split_sum_func(THD *thd, Item **ref_pointer_array,
 
1696
                                        List<Item> &fields)
 
1697
{
 
1698
  item->split_sum_func2(thd, ref_pointer_array, fields, &item, true);
 
1699
  Item_str_func::split_sum_func(thd, ref_pointer_array, fields);
 
1700
}
 
1701
 
 
1702
 
 
1703
void Item_func_make_set::fix_length_and_dec()
 
1704
{
 
1705
  max_length=arg_count-1;
 
1706
 
 
1707
  if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
 
1708
    return;
 
1709
  
 
1710
  for (uint i=0 ; i < arg_count ; i++)
 
1711
    max_length+=args[i]->max_length;
 
1712
 
 
1713
  used_tables_cache|=     item->used_tables();
 
1714
  not_null_tables_cache&= item->not_null_tables();
 
1715
  const_item_cache&=      item->const_item();
 
1716
  with_sum_func= with_sum_func || item->with_sum_func;
 
1717
}
 
1718
 
 
1719
 
 
1720
void Item_func_make_set::update_used_tables()
 
1721
{
 
1722
  Item_func::update_used_tables();
 
1723
  item->update_used_tables();
 
1724
  used_tables_cache|=item->used_tables();
 
1725
  const_item_cache&=item->const_item();
 
1726
}
 
1727
 
 
1728
 
 
1729
String *Item_func_make_set::val_str(String *str)
 
1730
{
 
1731
  assert(fixed == 1);
 
1732
  ulonglong bits;
 
1733
  bool first_found=0;
 
1734
  Item **ptr=args;
 
1735
  String *result=&my_empty_string;
 
1736
 
 
1737
  bits=item->val_int();
 
1738
  if ((null_value=item->null_value))
 
1739
    return NULL;
 
1740
 
 
1741
  if (arg_count < 64)
 
1742
    bits &= ((ulonglong) 1 << arg_count)-1;
 
1743
 
 
1744
  for (; bits; bits >>= 1, ptr++)
 
1745
  {
 
1746
    if (bits & 1)
 
1747
    {
 
1748
      String *res= (*ptr)->val_str(str);
 
1749
      if (res)                                  // Skip nulls
 
1750
      {
 
1751
        if (!first_found)
 
1752
        {                                       // First argument
 
1753
          first_found=1;
 
1754
          if (res != str)
 
1755
            result=res;                         // Use original string
 
1756
          else
 
1757
          {
 
1758
            if (tmp_str.copy(*res))             // Don't use 'str'
 
1759
              return &my_empty_string;
 
1760
            result= &tmp_str;
 
1761
          }
 
1762
        }
 
1763
        else
 
1764
        {
 
1765
          if (result != &tmp_str)
 
1766
          {                                     // Copy data to tmp_str
 
1767
            if (tmp_str.alloc(result->length()+res->length()+1) ||
 
1768
                tmp_str.copy(*result))
 
1769
              return &my_empty_string;
 
1770
            result= &tmp_str;
 
1771
          }
 
1772
          if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
 
1773
            return &my_empty_string;
 
1774
        }
 
1775
      }
 
1776
    }
 
1777
  }
 
1778
  return result;
 
1779
}
 
1780
 
 
1781
 
 
1782
Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg)
 
1783
{
 
1784
  Item *new_item= item->transform(transformer, arg);
 
1785
  if (!new_item)
 
1786
    return 0;
 
1787
 
 
1788
  /*
 
1789
    THD::change_item_tree() should be called only if the tree was
 
1790
    really transformed, i.e. when a new item has been created.
 
1791
    Otherwise we'll be allocating a lot of unnecessary memory for
 
1792
    change records at each execution.
 
1793
  */
 
1794
  if (item != new_item)
 
1795
    current_thd->change_item_tree(&item, new_item);
 
1796
  return Item_str_func::transform(transformer, arg);
 
1797
}
 
1798
 
 
1799
 
 
1800
void Item_func_make_set::print(String *str, enum_query_type query_type)
 
1801
{
 
1802
  str->append(STRING_WITH_LEN("make_set("));
 
1803
  item->print(str, query_type);
 
1804
  if (arg_count)
 
1805
  {
 
1806
    str->append(',');
 
1807
    print_args(str, 0, query_type);
 
1808
  }
 
1809
  str->append(')');
 
1810
}
 
1811
 
 
1812
 
 
1813
String *Item_func_char::val_str(String *str)
 
1814
{
 
1815
  assert(fixed == 1);
 
1816
  str->length(0);
 
1817
  str->set_charset(collation.collation);
 
1818
  for (uint i=0 ; i < arg_count ; i++)
 
1819
  {
 
1820
    int32 num=(int32) args[i]->val_int();
 
1821
    if (!args[i]->null_value)
 
1822
    {
 
1823
      char char_num= (char) num;
 
1824
      if (num&0xFF000000L) {
 
1825
        str->append((char)(num>>24));
 
1826
        goto b2;
 
1827
      } else if (num&0xFF0000L) {
 
1828
    b2:        str->append((char)(num>>16));
 
1829
        goto b1;
 
1830
      } else if (num&0xFF00L) {
 
1831
    b1:        str->append((char)(num>>8));
 
1832
      }
 
1833
      str->append(&char_num, 1);
 
1834
    }
 
1835
  }
 
1836
  str->realloc(str->length());                  // Add end 0 (for Purify)
 
1837
  return check_well_formed_result(str);
 
1838
}
 
1839
 
 
1840
 
 
1841
inline String* alloc_buffer(String *res,String *str,String *tmp_value,
 
1842
                            ulong length)
 
1843
{
 
1844
  if (res->alloced_length() < length)
 
1845
  {
 
1846
    if (str->alloced_length() >= length)
 
1847
    {
 
1848
      (void) str->copy(*res);
 
1849
      str->length(length);
 
1850
      return str;
 
1851
    }
 
1852
    if (tmp_value->alloc(length))
 
1853
      return 0;
 
1854
    (void) tmp_value->copy(*res);
 
1855
    tmp_value->length(length);
 
1856
    return tmp_value;
 
1857
  }
 
1858
  res->length(length);
 
1859
  return res;
 
1860
}
 
1861
 
 
1862
 
 
1863
void Item_func_repeat::fix_length_and_dec()
 
1864
{
 
1865
  collation.set(args[0]->collation);
 
1866
  if (args[1]->const_item())
 
1867
  {
 
1868
    /* must be longlong to avoid truncation */
 
1869
    longlong count= args[1]->val_int();
 
1870
 
 
1871
    /* Assumes that the maximum length of a String is < INT_MAX32. */
 
1872
    /* Set here so that rest of code sees out-of-bound value as such. */
 
1873
    if (count > INT_MAX32)
 
1874
      count= INT_MAX32;
 
1875
 
 
1876
    ulonglong max_result_length= (ulonglong) args[0]->max_length * count;
 
1877
    if (max_result_length >= MAX_BLOB_WIDTH)
 
1878
    {
 
1879
      max_result_length= MAX_BLOB_WIDTH;
 
1880
      maybe_null= 1;
 
1881
    }
 
1882
    max_length= (ulong) max_result_length;
 
1883
  }
 
1884
  else
 
1885
  {
 
1886
    max_length= MAX_BLOB_WIDTH;
 
1887
    maybe_null= 1;
 
1888
  }
 
1889
}
 
1890
 
 
1891
/**
 
1892
  Item_func_repeat::str is carefully written to avoid reallocs
 
1893
  as much as possible at the cost of a local buffer
 
1894
*/
 
1895
 
 
1896
String *Item_func_repeat::val_str(String *str)
 
1897
{
 
1898
  assert(fixed == 1);
 
1899
  uint length,tot_length;
 
1900
  char *to;
 
1901
  /* must be longlong to avoid truncation */
 
1902
  longlong count= args[1]->val_int();
 
1903
  String *res= args[0]->val_str(str);
 
1904
 
 
1905
  if (args[0]->null_value || args[1]->null_value)
 
1906
    goto err;                           // string and/or delim are null
 
1907
  null_value= 0;
 
1908
 
 
1909
  if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
 
1910
    return &my_empty_string;
 
1911
 
 
1912
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
1913
  /* Bounds check on count:  If this is triggered, we will error. */
 
1914
  if ((ulonglong) count > INT_MAX32)
 
1915
    count= INT_MAX32;
 
1916
  if (count == 1)                       // To avoid reallocs
 
1917
    return res;
 
1918
  length=res->length();
 
1919
  // Safe length check
 
1920
  if (length > current_thd->variables.max_allowed_packet / (uint) count)
 
1921
  {
 
1922
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
1923
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
1924
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
1925
                        func_name(), current_thd->variables.max_allowed_packet);
 
1926
    goto err;
 
1927
  }
 
1928
  tot_length= length*(uint) count;
 
1929
  if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
 
1930
    goto err;
 
1931
 
 
1932
  to=(char*) res->ptr()+length;
 
1933
  while (--count)
 
1934
  {
 
1935
    memcpy(to,res->ptr(),length);
 
1936
    to+=length;
 
1937
  }
 
1938
  return (res);
 
1939
 
 
1940
err:
 
1941
  null_value=1;
 
1942
  return 0;
 
1943
}
 
1944
 
 
1945
 
 
1946
void Item_func_rpad::fix_length_and_dec()
 
1947
{
 
1948
  // Handle character set for args[0] and args[2].
 
1949
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
 
1950
    return;
 
1951
  if (args[1]->const_item())
 
1952
  {
 
1953
    ulonglong length= 0;
 
1954
 
 
1955
    if (collation.collation->mbmaxlen > 0)
 
1956
    {
 
1957
      ulonglong temp= (ulonglong) args[1]->val_int();
 
1958
 
 
1959
      /* Assumes that the maximum length of a String is < INT_MAX32. */
 
1960
      /* Set here so that rest of code sees out-of-bound value as such. */
 
1961
      if (temp > INT_MAX32)
 
1962
        temp = INT_MAX32;
 
1963
 
 
1964
      length= temp * collation.collation->mbmaxlen;
 
1965
    }
 
1966
 
 
1967
    if (length >= MAX_BLOB_WIDTH)
 
1968
    {
 
1969
      length= MAX_BLOB_WIDTH;
 
1970
      maybe_null= 1;
 
1971
    }
 
1972
    max_length= (ulong) length;
 
1973
  }
 
1974
  else
 
1975
  {
 
1976
    max_length= MAX_BLOB_WIDTH;
 
1977
    maybe_null= 1;
 
1978
  }
 
1979
}
 
1980
 
 
1981
 
 
1982
String *Item_func_rpad::val_str(String *str)
 
1983
{
 
1984
  assert(fixed == 1);
 
1985
  uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
 
1986
  char *to;
 
1987
  const char *ptr_pad;
 
1988
  /* must be longlong to avoid truncation */
 
1989
  longlong count= args[1]->val_int();
 
1990
  longlong byte_count;
 
1991
  String *res= args[0]->val_str(str);
 
1992
  String *rpad= args[2]->val_str(&rpad_str);
 
1993
 
 
1994
  if (!res || args[1]->null_value || !rpad || 
 
1995
      ((count < 0) && !args[1]->unsigned_flag))
 
1996
    goto err;
 
1997
  null_value=0;
 
1998
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
1999
  /* Set here so that rest of code sees out-of-bound value as such. */
 
2000
  if ((ulonglong) count > INT_MAX32)
 
2001
    count= INT_MAX32;
 
2002
  if (count <= (res_char_length= res->numchars()))
 
2003
  {                                             // String to pad is big enough
 
2004
    res->length(res->charpos((int) count));     // Shorten result if longer
 
2005
    return (res);
 
2006
  }
 
2007
  pad_char_length= rpad->numchars();
 
2008
 
 
2009
  byte_count= count * collation.collation->mbmaxlen;
 
2010
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
 
2011
  {
 
2012
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2013
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
2014
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
2015
                        func_name(), current_thd->variables.max_allowed_packet);
 
2016
    goto err;
 
2017
  }
 
2018
  if (args[2]->null_value || !pad_char_length)
 
2019
    goto err;
 
2020
  res_byte_length= res->length();       /* Must be done before alloc_buffer */
 
2021
  if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
 
2022
    goto err;
 
2023
 
 
2024
  to= (char*) res->ptr()+res_byte_length;
 
2025
  ptr_pad=rpad->ptr();
 
2026
  pad_byte_length= rpad->length();
 
2027
  count-= res_char_length;
 
2028
  for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
 
2029
  {
 
2030
    memcpy(to,ptr_pad,pad_byte_length);
 
2031
    to+= pad_byte_length;
 
2032
  }
 
2033
  if (count)
 
2034
  {
 
2035
    pad_byte_length= rpad->charpos((int) count);
 
2036
    memcpy(to,ptr_pad,(size_t) pad_byte_length);
 
2037
    to+= pad_byte_length;
 
2038
  }
 
2039
  res->length(to- (char*) res->ptr());
 
2040
  return (res);
 
2041
 
 
2042
 err:
 
2043
  null_value=1;
 
2044
  return 0;
 
2045
}
 
2046
 
 
2047
 
 
2048
void Item_func_lpad::fix_length_and_dec()
 
2049
{
 
2050
  // Handle character set for args[0] and args[2].
 
2051
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
 
2052
    return;
 
2053
  
 
2054
  if (args[1]->const_item())
 
2055
  {
 
2056
    ulonglong length= 0;
 
2057
 
 
2058
    if (collation.collation->mbmaxlen > 0)
 
2059
    {
 
2060
      ulonglong temp= (ulonglong) args[1]->val_int();
 
2061
 
 
2062
      /* Assumes that the maximum length of a String is < INT_MAX32. */
 
2063
      /* Set here so that rest of code sees out-of-bound value as such. */
 
2064
      if (temp > INT_MAX32)
 
2065
        temp= INT_MAX32;
 
2066
 
 
2067
      length= temp * collation.collation->mbmaxlen;
 
2068
    }
 
2069
 
 
2070
    if (length >= MAX_BLOB_WIDTH)
 
2071
    {
 
2072
      length= MAX_BLOB_WIDTH;
 
2073
      maybe_null= 1;
 
2074
    }
 
2075
    max_length= (ulong) length;
 
2076
  }
 
2077
  else
 
2078
  {
 
2079
    max_length= MAX_BLOB_WIDTH;
 
2080
    maybe_null= 1;
 
2081
  }
 
2082
}
 
2083
 
 
2084
 
 
2085
String *Item_func_lpad::val_str(String *str)
 
2086
{
 
2087
  assert(fixed == 1);
 
2088
  uint32 res_char_length,pad_char_length;
 
2089
  /* must be longlong to avoid truncation */
 
2090
  longlong count= args[1]->val_int();
 
2091
  longlong byte_count;
 
2092
  String *res= args[0]->val_str(&tmp_value);
 
2093
  String *pad= args[2]->val_str(&lpad_str);
 
2094
 
 
2095
  if (!res || args[1]->null_value || !pad ||  
 
2096
      ((count < 0) && !args[1]->unsigned_flag))
 
2097
    goto err;  
 
2098
  null_value=0;
 
2099
  /* Assumes that the maximum length of a String is < INT_MAX32. */
 
2100
  /* Set here so that rest of code sees out-of-bound value as such. */
 
2101
  if ((ulonglong) count > INT_MAX32)
 
2102
    count= INT_MAX32;
 
2103
 
 
2104
  res_char_length= res->numchars();
 
2105
 
 
2106
  if (count <= res_char_length)
 
2107
  {
 
2108
    res->length(res->charpos((int) count));
 
2109
    return res;
 
2110
  }
 
2111
  
 
2112
  pad_char_length= pad->numchars();
 
2113
  byte_count= count * collation.collation->mbmaxlen;
 
2114
  
 
2115
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
 
2116
  {
 
2117
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2118
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
2119
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
2120
                        func_name(), current_thd->variables.max_allowed_packet);
 
2121
    goto err;
 
2122
  }
 
2123
 
 
2124
  if (args[2]->null_value || !pad_char_length ||
 
2125
      str->alloc((uint32) byte_count))
 
2126
    goto err;
 
2127
  
 
2128
  str->length(0);
 
2129
  str->set_charset(collation.collation);
 
2130
  count-= res_char_length;
 
2131
  while (count >= pad_char_length)
 
2132
  {
 
2133
    str->append(*pad);
 
2134
    count-= pad_char_length;
 
2135
  }
 
2136
  if (count > 0)
 
2137
    str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
 
2138
 
 
2139
  str->append(*res);
 
2140
  null_value= 0;
 
2141
  return str;
 
2142
 
 
2143
err:
 
2144
  null_value= 1;
 
2145
  return 0;
 
2146
}
 
2147
 
 
2148
 
 
2149
String *Item_func_conv::val_str(String *str)
 
2150
{
 
2151
  assert(fixed == 1);
 
2152
  String *res= args[0]->val_str(str);
 
2153
  char *endptr,ans[65],*ptr;
 
2154
  longlong dec;
 
2155
  int from_base= (int) args[1]->val_int();
 
2156
  int to_base= (int) args[2]->val_int();
 
2157
  int err;
 
2158
 
 
2159
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
 
2160
      abs(to_base) > 36 || abs(to_base) < 2 ||
 
2161
      abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
 
2162
  {
 
2163
    null_value= 1;
 
2164
    return NULL;
 
2165
  }
 
2166
  null_value= 0;
 
2167
  unsigned_flag= !(from_base < 0);
 
2168
 
 
2169
  if (from_base < 0)
 
2170
    dec= my_strntoll(res->charset(), res->ptr(), res->length(),
 
2171
                     -from_base, &endptr, &err);
 
2172
  else
 
2173
    dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
 
2174
                                 from_base, &endptr, &err);
 
2175
 
 
2176
  ptr= longlong2str(dec, ans, to_base);
 
2177
  if (str->copy(ans, (uint32) (ptr-ans), default_charset()))
 
2178
    return &my_empty_string;
 
2179
  return str;
 
2180
}
 
2181
 
 
2182
 
 
2183
String *Item_func_conv_charset::val_str(String *str)
 
2184
{
 
2185
  assert(fixed == 1);
 
2186
  if (use_cached_value)
 
2187
    return null_value ? 0 : &str_value;
 
2188
  String *arg= args[0]->val_str(str);
 
2189
  uint dummy_errors;
 
2190
  if (!arg)
 
2191
  {
 
2192
    null_value=1;
 
2193
    return 0;
 
2194
  }
 
2195
  null_value= str_value.copy(arg->ptr(),arg->length(),arg->charset(),
 
2196
                             conv_charset, &dummy_errors);
 
2197
  return null_value ? 0 : check_well_formed_result(&str_value);
 
2198
}
 
2199
 
 
2200
void Item_func_conv_charset::fix_length_and_dec()
 
2201
{
 
2202
  collation.set(conv_charset, DERIVATION_IMPLICIT);
 
2203
  max_length = args[0]->max_length*conv_charset->mbmaxlen;
 
2204
}
 
2205
 
 
2206
void Item_func_conv_charset::print(String *str, enum_query_type query_type)
 
2207
{
 
2208
  str->append(STRING_WITH_LEN("convert("));
 
2209
  args[0]->print(str, query_type);
 
2210
  str->append(STRING_WITH_LEN(" using "));
 
2211
  str->append(conv_charset->csname);
 
2212
  str->append(')');
 
2213
}
 
2214
 
 
2215
String *Item_func_set_collation::val_str(String *str)
 
2216
{
 
2217
  assert(fixed == 1);
 
2218
  str=args[0]->val_str(str);
 
2219
  if ((null_value=args[0]->null_value))
 
2220
    return 0;
 
2221
  str->set_charset(collation.collation);
 
2222
  return str;
 
2223
}
 
2224
 
 
2225
void Item_func_set_collation::fix_length_and_dec()
 
2226
{
 
2227
  CHARSET_INFO *set_collation;
 
2228
  const char *colname;
 
2229
  String tmp, *str= args[1]->val_str(&tmp);
 
2230
  colname= str->c_ptr();
 
2231
  if (colname == binary_keyword)
 
2232
    set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
 
2233
                                         MY_CS_BINSORT,MYF(0));
 
2234
  else
 
2235
  {
 
2236
    if (!(set_collation= get_charset_by_name(colname,MYF(0))))
 
2237
    {
 
2238
      my_error(ER_UNKNOWN_COLLATION, MYF(0), colname);
 
2239
      return;
 
2240
    }
 
2241
  }
 
2242
 
 
2243
  if (!set_collation || 
 
2244
      !my_charset_same(args[0]->collation.collation,set_collation))
 
2245
  {
 
2246
    my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
 
2247
             colname, args[0]->collation.collation->csname);
 
2248
    return;
 
2249
  }
 
2250
  collation.set(set_collation, DERIVATION_EXPLICIT,
 
2251
                args[0]->collation.repertoire);
 
2252
  max_length= args[0]->max_length;
 
2253
}
 
2254
 
 
2255
 
 
2256
bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
 
2257
{
 
2258
  /* Assume we don't have rtti */
 
2259
  if (this == item)
 
2260
    return 1;
 
2261
  if (item->type() != FUNC_ITEM)
 
2262
    return 0;
 
2263
  Item_func *item_func=(Item_func*) item;
 
2264
  if (arg_count != item_func->arg_count ||
 
2265
      functype() != item_func->functype())
 
2266
    return 0;
 
2267
  Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
 
2268
  if (collation.collation != item_func_sc->collation.collation)
 
2269
    return 0;
 
2270
  for (uint i=0; i < arg_count ; i++)
 
2271
    if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
 
2272
      return 0;
 
2273
  return 1;
 
2274
}
 
2275
 
 
2276
 
 
2277
void Item_func_set_collation::print(String *str, enum_query_type query_type)
 
2278
{
 
2279
  str->append('(');
 
2280
  args[0]->print(str, query_type);
 
2281
  str->append(STRING_WITH_LEN(" collate "));
 
2282
  assert(args[1]->basic_const_item() &&
 
2283
              args[1]->type() == Item::STRING_ITEM);
 
2284
  args[1]->str_value.print(str);
 
2285
  str->append(')');
 
2286
}
 
2287
 
 
2288
String *Item_func_charset::val_str(String *str)
 
2289
{
 
2290
  assert(fixed == 1);
 
2291
  uint dummy_errors;
 
2292
 
 
2293
  CHARSET_INFO *cs= args[0]->collation.collation; 
 
2294
  null_value= 0;
 
2295
  str->copy(cs->csname, strlen(cs->csname),
 
2296
            &my_charset_latin1, collation.collation, &dummy_errors);
 
2297
  return str;
 
2298
}
 
2299
 
 
2300
String *Item_func_collation::val_str(String *str)
 
2301
{
 
2302
  assert(fixed == 1);
 
2303
  uint dummy_errors;
 
2304
  CHARSET_INFO *cs= args[0]->collation.collation; 
 
2305
 
 
2306
  null_value= 0;
 
2307
  str->copy(cs->name, strlen(cs->name),
 
2308
            &my_charset_latin1, collation.collation, &dummy_errors);
 
2309
  return str;
 
2310
}
 
2311
 
 
2312
 
 
2313
void Item_func_weight_string::fix_length_and_dec()
 
2314
{
 
2315
  CHARSET_INFO *cs= args[0]->collation.collation;
 
2316
  collation.set(&my_charset_bin, args[0]->collation.derivation);
 
2317
  flags= my_strxfrm_flag_normalize(flags, cs->levels_for_order);
 
2318
  max_length= cs->mbmaxlen * max(args[0]->max_length, nweights);
 
2319
  maybe_null= 1;
 
2320
}
 
2321
 
 
2322
 
 
2323
/* Return a weight_string according to collation */
 
2324
String *Item_func_weight_string::val_str(String *str)
 
2325
{
 
2326
  String *res;
 
2327
  CHARSET_INFO *cs= args[0]->collation.collation;
 
2328
  uint tmp_length, frm_length;
 
2329
  assert(fixed == 1);
 
2330
 
 
2331
  if (args[0]->result_type() != STRING_RESULT ||
 
2332
      !(res= args[0]->val_str(str)))
 
2333
    goto nl;
 
2334
  
 
2335
  tmp_length= cs->coll->strnxfrmlen(cs, cs->mbmaxlen *
 
2336
                                        max(res->length(), nweights));
 
2337
 
 
2338
  if (tmp_value.alloc(tmp_length))
 
2339
    goto nl;
 
2340
 
 
2341
  frm_length= cs->coll->strnxfrm(cs,
 
2342
                                 (uchar*) tmp_value.ptr(), tmp_length,
 
2343
                                 nweights ? nweights : tmp_length,
 
2344
                                 (const uchar*) res->ptr(), res->length(),
 
2345
                                 flags);
 
2346
  tmp_value.length(frm_length);
 
2347
  null_value= 0;
 
2348
  return &tmp_value;
 
2349
 
 
2350
nl:
 
2351
  null_value= 1;
 
2352
  return 0;
 
2353
}
 
2354
 
 
2355
 
 
2356
String *Item_func_hex::val_str(String *str)
 
2357
{
 
2358
  String *res;
 
2359
  assert(fixed == 1);
 
2360
  if (args[0]->result_type() != STRING_RESULT)
 
2361
  {
 
2362
    ulonglong dec;
 
2363
    char ans[65],*ptr;
 
2364
    /* Return hex of unsigned longlong value */
 
2365
    if (args[0]->result_type() == REAL_RESULT ||
 
2366
        args[0]->result_type() == DECIMAL_RESULT)
 
2367
    {
 
2368
      double val= args[0]->val_real();
 
2369
      if ((val <= (double) LONGLONG_MIN) || 
 
2370
          (val >= (double) (ulonglong) ULONGLONG_MAX))
 
2371
        dec=  ~(longlong) 0;
 
2372
      else
 
2373
        dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
 
2374
    }
 
2375
    else
 
2376
      dec= (ulonglong) args[0]->val_int();
 
2377
 
 
2378
    if ((null_value= args[0]->null_value))
 
2379
      return 0;
 
2380
    ptr= longlong2str(dec,ans,16);
 
2381
    if (str->copy(ans,(uint32) (ptr-ans),default_charset()))
 
2382
      return &my_empty_string;                  // End of memory
 
2383
    return str;
 
2384
  }
 
2385
 
 
2386
  /* Convert given string to a hex string, character by character */
 
2387
  res= args[0]->val_str(str);
 
2388
  if (!res || tmp_value.alloc(res->length()*2+1))
 
2389
  {
 
2390
    null_value=1;
 
2391
    return 0;
 
2392
  }
 
2393
  null_value=0;
 
2394
  tmp_value.length(res->length()*2);
 
2395
 
 
2396
  octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
 
2397
  return &tmp_value;
 
2398
}
 
2399
 
 
2400
  /** Convert given hex string to a binary string. */
 
2401
 
 
2402
String *Item_func_unhex::val_str(String *str)
 
2403
{
 
2404
  const char *from, *end;
 
2405
  char *to;
 
2406
  String *res;
 
2407
  uint length;
 
2408
  assert(fixed == 1);
 
2409
 
 
2410
  res= args[0]->val_str(str);
 
2411
  if (!res || tmp_value.alloc(length= (1+res->length())/2))
 
2412
  {
 
2413
    null_value=1;
 
2414
    return 0;
 
2415
  }
 
2416
 
 
2417
  from= res->ptr();
 
2418
  null_value= 0;
 
2419
  tmp_value.length(length);
 
2420
  to= (char*) tmp_value.ptr();
 
2421
  if (res->length() % 2)
 
2422
  {
 
2423
    int hex_char;
 
2424
    *to++= hex_char= hexchar_to_int(*from++);
 
2425
    if ((null_value= (hex_char == -1)))
 
2426
      return 0;
 
2427
  }
 
2428
  for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
 
2429
  {
 
2430
    int hex_char;
 
2431
    *to= (hex_char= hexchar_to_int(from[0])) << 4;
 
2432
    if ((null_value= (hex_char == -1)))
 
2433
      return 0;
 
2434
    *to|= hex_char= hexchar_to_int(from[1]);
 
2435
    if ((null_value= (hex_char == -1)))
 
2436
      return 0;
 
2437
  }
 
2438
  return &tmp_value;
 
2439
}
 
2440
 
 
2441
 
 
2442
void Item_func_binary::print(String *str, enum_query_type query_type)
 
2443
{
 
2444
  str->append(STRING_WITH_LEN("cast("));
 
2445
  args[0]->print(str, query_type);
 
2446
  str->append(STRING_WITH_LEN(" as binary)"));
 
2447
}
 
2448
 
 
2449
 
 
2450
#include <my_dir.h>
 
2451
 
 
2452
String *Item_load_file::val_str(String *str)
 
2453
{
 
2454
  assert(fixed == 1);
 
2455
  String *file_name;
 
2456
  File file;
 
2457
  struct stat stat_info;
 
2458
  char path[FN_REFLEN];
 
2459
 
 
2460
  if (!(file_name= args[0]->val_str(str)))
 
2461
    goto err;
 
2462
 
 
2463
  (void) fn_format(path, file_name->c_ptr(), mysql_real_data_home, "",
 
2464
                   MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
 
2465
 
 
2466
  /* Read only allowed from within dir specified by secure_file_priv */
 
2467
  if (opt_secure_file_priv &&
 
2468
      strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv)))
 
2469
    goto err;
 
2470
 
 
2471
  if (stat(path, &stat_info))
 
2472
    goto err;
 
2473
 
 
2474
  if (!(stat_info.st_mode & S_IROTH))
 
2475
  {
 
2476
    /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
 
2477
    goto err;
 
2478
  }
 
2479
  if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
 
2480
  {
 
2481
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
2482
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
 
2483
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
 
2484
                        func_name(), current_thd->variables.max_allowed_packet);
 
2485
    goto err;
 
2486
  }
 
2487
  if (tmp_value.alloc(stat_info.st_size))
 
2488
    goto err;
 
2489
  if ((file = my_open(file_name->c_ptr(), O_RDONLY, MYF(0))) < 0)
 
2490
    goto err;
 
2491
  if (my_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size, MYF(MY_NABP)))
 
2492
  {
 
2493
    my_close(file, MYF(0));
 
2494
    goto err;
 
2495
  }
 
2496
  tmp_value.length(stat_info.st_size);
 
2497
  my_close(file, MYF(0));
 
2498
  null_value = 0;
 
2499
  return(&tmp_value);
 
2500
 
 
2501
err:
 
2502
  null_value = 1;
 
2503
  return(0);
 
2504
}
 
2505
 
 
2506
 
 
2507
String* Item_func_export_set::val_str(String* str)
 
2508
{
 
2509
  assert(fixed == 1);
 
2510
  ulonglong the_set = (ulonglong) args[0]->val_int();
 
2511
  String yes_buf, *yes;
 
2512
  yes = args[1]->val_str(&yes_buf);
 
2513
  String no_buf, *no;
 
2514
  no = args[2]->val_str(&no_buf);
 
2515
  String *sep = NULL, sep_buf ;
 
2516
 
 
2517
  uint num_set_values = 64;
 
2518
  ulonglong mask = 0x1;
 
2519
  str->length(0);
 
2520
  str->set_charset(collation.collation);
 
2521
 
 
2522
  /* Check if some argument is a NULL value */
 
2523
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
 
2524
  {
 
2525
    null_value=1;
 
2526
    return 0;
 
2527
  }
 
2528
  /*
 
2529
    Arg count can only be 3, 4 or 5 here. This is guaranteed from the
 
2530
    grammar for EXPORT_SET()
 
2531
  */
 
2532
  switch(arg_count) {
 
2533
  case 5:
 
2534
    num_set_values = (uint) args[4]->val_int();
 
2535
    if (num_set_values > 64)
 
2536
      num_set_values=64;
 
2537
    if (args[4]->null_value)
 
2538
    {
 
2539
      null_value=1;
 
2540
      return 0;
 
2541
    }
 
2542
    /* Fall through */
 
2543
  case 4:
 
2544
    if (!(sep = args[3]->val_str(&sep_buf)))    // Only true if NULL
 
2545
    {
 
2546
      null_value=1;
 
2547
      return 0;
 
2548
    }
 
2549
    break;
 
2550
  case 3:
 
2551
    {
 
2552
      /* errors is not checked - assume "," can always be converted */
 
2553
      uint errors;
 
2554
      sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin, collation.collation, &errors);
 
2555
      sep = &sep_buf;
 
2556
    }
 
2557
    break;
 
2558
  default:
 
2559
    assert(0); // cannot happen
 
2560
  }
 
2561
  null_value=0;
 
2562
 
 
2563
  for (uint i = 0; i < num_set_values; i++, mask = (mask << 1))
 
2564
  {
 
2565
    if (the_set & mask)
 
2566
      str->append(*yes);
 
2567
    else
 
2568
      str->append(*no);
 
2569
    if (i != num_set_values - 1)
 
2570
      str->append(*sep);
 
2571
  }
 
2572
  return str;
 
2573
}
 
2574
 
 
2575
void Item_func_export_set::fix_length_and_dec()
 
2576
{
 
2577
  uint length=max(args[1]->max_length,args[2]->max_length);
 
2578
  uint sep_length=(arg_count > 3 ? args[3]->max_length : 1);
 
2579
  max_length=length*64+sep_length*63;
 
2580
 
 
2581
  if (agg_arg_charsets(collation, args+1, min(4,arg_count)-1,
 
2582
                       MY_COLL_ALLOW_CONV, 1))
 
2583
    return;
 
2584
}
 
2585
 
 
2586
 
 
2587
#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))
 
2588
 
 
2589
/**
 
2590
  QUOTE() function returns argument string in single quotes suitable for
 
2591
  using in a SQL statement.
 
2592
 
 
2593
  Adds a \\ before all characters that needs to be escaped in a SQL string.
 
2594
  We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
 
2595
  running commands from a file in windows.
 
2596
 
 
2597
  This function is very useful when you want to generate SQL statements.
 
2598
 
 
2599
  @note
 
2600
    QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).
 
2601
 
 
2602
  @retval
 
2603
    str    Quoted string
 
2604
  @retval
 
2605
    NULL           Out of memory.
 
2606
*/
 
2607
 
 
2608
String *Item_func_quote::val_str(String *str)
 
2609
{
 
2610
  assert(fixed == 1);
 
2611
  /*
 
2612
    Bit mask that has 1 for set for the position of the following characters:
 
2613
    0, \, ' and ^Z
 
2614
  */
 
2615
 
 
2616
  static uchar escmask[32]=
 
2617
  {
 
2618
    0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
 
2619
    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
 
2620
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
 
2621
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
 
2622
  };
 
2623
 
 
2624
  char *from, *to, *end, *start;
 
2625
  String *arg= args[0]->val_str(str);
 
2626
  uint arg_length, new_length;
 
2627
  if (!arg)                                     // Null argument
 
2628
  {
 
2629
    /* Return the string 'NULL' */
 
2630
    str->copy(STRING_WITH_LEN("NULL"), collation.collation);
 
2631
    null_value= 0;
 
2632
    return str;
 
2633
  }
 
2634
 
 
2635
  arg_length= arg->length();
 
2636
  new_length= arg_length+2; /* for beginning and ending ' signs */
 
2637
 
 
2638
  for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
 
2639
    new_length+= get_esc_bit(escmask, (uchar) *from);
 
2640
 
 
2641
  if (tmp_value.alloc(new_length))
 
2642
    goto null;
 
2643
 
 
2644
  /*
 
2645
    We replace characters from the end to the beginning
 
2646
  */
 
2647
  to= (char*) tmp_value.ptr() + new_length - 1;
 
2648
  *to--= '\'';
 
2649
  for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
 
2650
  {
 
2651
    /*
 
2652
      We can't use the bitmask here as we want to replace \O and ^Z with 0
 
2653
      and Z
 
2654
    */
 
2655
    switch (*end)  {
 
2656
    case 0:
 
2657
      *to--= '0';
 
2658
      *to=   '\\';
 
2659
      break;
 
2660
    case '\032':
 
2661
      *to--= 'Z';
 
2662
      *to=   '\\';
 
2663
      break;
 
2664
    case '\'':
 
2665
    case '\\':
 
2666
      *to--= *end;
 
2667
      *to=   '\\';
 
2668
      break;
 
2669
    default:
 
2670
      *to= *end;
 
2671
      break;
 
2672
    }
 
2673
  }
 
2674
  *to= '\'';
 
2675
  tmp_value.length(new_length);
 
2676
  tmp_value.set_charset(collation.collation);
 
2677
  null_value= 0;
 
2678
  return &tmp_value;
 
2679
 
 
2680
null:
 
2681
  null_value= 1;
 
2682
  return 0;
 
2683
}
 
2684
 
 
2685
longlong Item_func_uncompressed_length::val_int()
 
2686
{
 
2687
  assert(fixed == 1);
 
2688
  String *res= args[0]->val_str(&value);
 
2689
  if (!res)
 
2690
  {
 
2691
    null_value=1;
 
2692
    return 0; /* purecov: inspected */
 
2693
  }
 
2694
  null_value=0;
 
2695
  if (res->is_empty()) return 0;
 
2696
 
 
2697
  /*
 
2698
    res->ptr() using is safe because we have tested that string is not empty,
 
2699
    res->c_ptr() is not used because:
 
2700
      - we do not need \0 terminated string to get first 4 bytes
 
2701
      - c_ptr() tests simbol after string end (uninitialiozed memory) which
 
2702
        confuse valgrind
 
2703
  */
 
2704
  return uint4korr(res->ptr()) & 0x3FFFFFFF;
 
2705
}
 
2706
 
 
2707
longlong Item_func_crc32::val_int()
 
2708
{
 
2709
  assert(fixed == 1);
 
2710
  String *res=args[0]->val_str(&value);
 
2711
  if (!res)
 
2712
  {
 
2713
    null_value=1;
 
2714
    return 0; /* purecov: inspected */
 
2715
  }
 
2716
  null_value=0;
 
2717
  return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
 
2718
}
 
2719
 
 
2720
#ifdef HAVE_COMPRESS
 
2721
#include "zlib.h"
 
2722
 
 
2723
String *Item_func_compress::val_str(String *str)
 
2724
{
 
2725
  int err= Z_OK, code;
 
2726
  ulong new_size;
 
2727
  String *res;
 
2728
  Byte *body;
 
2729
  char *tmp, *last_char;
 
2730
  assert(fixed == 1);
 
2731
 
 
2732
  if (!(res= args[0]->val_str(str)))
 
2733
  {
 
2734
    null_value= 1;
 
2735
    return 0;
 
2736
  }
 
2737
  null_value= 0;
 
2738
  if (res->is_empty()) return res;
 
2739
 
 
2740
  /*
 
2741
    Citation from zlib.h (comment for compress function):
 
2742
 
 
2743
    Compresses the source buffer into the destination buffer.  sourceLen is
 
2744
    the byte length of the source buffer. Upon entry, destLen is the total
 
2745
    size of the destination buffer, which must be at least 0.1% larger than
 
2746
    sourceLen plus 12 bytes.
 
2747
    We assume here that the buffer can't grow more than .25 %.
 
2748
  */
 
2749
  new_size= res->length() + res->length() / 5 + 12;
 
2750
 
 
2751
  // Check new_size overflow: new_size <= res->length()
 
2752
  if (((uint32) (new_size+5) <= res->length()) || 
 
2753
      buffer.realloc((uint32) new_size + 4 + 1))
 
2754
  {
 
2755
    null_value= 1;
 
2756
    return 0;
 
2757
  }
 
2758
 
 
2759
  body= ((Byte*)buffer.ptr()) + 4;
 
2760
 
 
2761
  // As far as we have checked res->is_empty() we can use ptr()
 
2762
  if ((err= compress(body, &new_size,
 
2763
                     (const Bytef*)res->ptr(), res->length())) != Z_OK)
 
2764
  {
 
2765
    code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
 
2766
    push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
 
2767
    null_value= 1;
 
2768
    return 0;
 
2769
  }
 
2770
 
 
2771
  tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
 
2772
  int4store(tmp, res->length() & 0x3FFFFFFF);
 
2773
 
 
2774
  /* This is to ensure that things works for CHAR fields, which trim ' ': */
 
2775
  last_char= ((char*)body)+new_size-1;
 
2776
  if (*last_char == ' ')
 
2777
  {
 
2778
    *++last_char= '.';
 
2779
    new_size++;
 
2780
  }
 
2781
 
 
2782
  buffer.length((uint32)new_size + 4);
 
2783
  return &buffer;
 
2784
}
 
2785
 
 
2786
 
 
2787
String *Item_func_uncompress::val_str(String *str)
 
2788
{
 
2789
  assert(fixed == 1);
 
2790
  String *res= args[0]->val_str(str);
 
2791
  ulong new_size;
 
2792
  int err;
 
2793
  uint code;
 
2794
 
 
2795
  if (!res)
 
2796
    goto err;
 
2797
  null_value= 0;
 
2798
  if (res->is_empty())
 
2799
    return res;
 
2800
 
 
2801
  /* If length is less than 4 bytes, data is corrupt */
 
2802
  if (res->length() <= 4)
 
2803
  {
 
2804
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
 
2805
                        ER_ZLIB_Z_DATA_ERROR,
 
2806
                        ER(ER_ZLIB_Z_DATA_ERROR));
 
2807
    goto err;
 
2808
  }
 
2809
 
 
2810
  /* Size of uncompressed data is stored as first 4 bytes of field */
 
2811
  new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
 
2812
  if (new_size > current_thd->variables.max_allowed_packet)
 
2813
  {
 
2814
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
 
2815
                        ER_TOO_BIG_FOR_UNCOMPRESS,
 
2816
                        ER(ER_TOO_BIG_FOR_UNCOMPRESS),
 
2817
                        current_thd->variables.max_allowed_packet);
 
2818
    goto err;
 
2819
  }
 
2820
  if (buffer.realloc((uint32)new_size))
 
2821
    goto err;
 
2822
 
 
2823
  if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
 
2824
                       ((const Bytef*)res->ptr())+4,res->length())) == Z_OK)
 
2825
  {
 
2826
    buffer.length((uint32) new_size);
 
2827
    return &buffer;
 
2828
  }
 
2829
 
 
2830
  code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
 
2831
         ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
 
2832
  push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
 
2833
 
 
2834
err:
 
2835
  null_value= 1;
 
2836
  return 0;
 
2837
}
 
2838
#endif
 
2839
 
 
2840
/*
 
2841
  UUID, as in
 
2842
    DCE 1.1: Remote Procedure Call,
 
2843
    Open Group Technical Standard Document Number C706, October 1997,
 
2844
    (supersedes C309 DCE: Remote Procedure Call 8/1994,
 
2845
    which was basis for ISO/IEC 11578:1996 specification)
 
2846
*/
 
2847
 
 
2848
static struct rand_struct uuid_rand;
 
2849
static uint nanoseq;
 
2850
static ulonglong uuid_time=0;
 
2851
static char clock_seq_and_node_str[]="-0000-000000000000";
 
2852
 
 
2853
/**
 
2854
  number of 100-nanosecond intervals between
 
2855
  1582-10-15 00:00:00.00 and 1970-01-01 00:00:00.00.
 
2856
*/
 
2857
#define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * 1000 * 10 )
 
2858
 
 
2859
#define UUID_VERSION      0x1000
 
2860
#define UUID_VARIANT      0x8000
 
2861
 
 
2862
static void tohex(char *to, uint from, uint len)
 
2863
{
 
2864
  to+= len;
 
2865
  while (len--)
 
2866
  {
 
2867
    *--to= _dig_vec_lower[from & 15];
 
2868
    from >>= 4;
 
2869
  }
 
2870
}
 
2871
 
 
2872
static void set_clock_seq_str()
 
2873
{
 
2874
  uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT;
 
2875
  tohex(clock_seq_and_node_str+1, clock_seq, 4);
 
2876
  nanoseq= 0;
 
2877
}
 
2878
 
 
2879
String *Item_func_uuid::val_str(String *str)
 
2880
{
 
2881
  assert(fixed == 1);
 
2882
  char *s;
 
2883
  THD *thd= current_thd;
 
2884
 
 
2885
  pthread_mutex_lock(&LOCK_uuid_generator);
 
2886
  if (! uuid_time) /* first UUID() call. initializing data */
 
2887
  {
 
2888
    ulong tmp=sql_rnd_with_mutex();
 
2889
    uchar mac[6];
 
2890
    int i;
 
2891
    if (my_gethwaddr(mac))
 
2892
    {
 
2893
      /* purecov: begin inspected */
 
2894
      /*
 
2895
        generating random "hardware addr"
 
2896
        and because specs explicitly specify that it should NOT correlate
 
2897
        with a clock_seq value (initialized random below), we use a separate
 
2898
        randominit() here
 
2899
      */
 
2900
      randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)global_query_id);
 
2901
      for (i=0; i < (int)sizeof(mac); i++)
 
2902
        mac[i]=(uchar)(my_rnd(&uuid_rand)*255);
 
2903
      /* purecov: end */    
 
2904
    }
 
2905
    s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1;
 
2906
    for (i=sizeof(mac)-1 ; i>=0 ; i--)
 
2907
    {
 
2908
      *--s=_dig_vec_lower[mac[i] & 15];
 
2909
      *--s=_dig_vec_lower[mac[i] >> 4];
 
2910
    }
 
2911
    randominit(&uuid_rand, tmp + (ulong) server_start_time,
 
2912
               tmp + (ulong) thd->status_var.bytes_sent);
 
2913
    set_clock_seq_str();
 
2914
  }
 
2915
 
 
2916
  ulonglong tv=my_getsystime() + UUID_TIME_OFFSET + nanoseq;
 
2917
  if (unlikely(tv < uuid_time))
 
2918
    set_clock_seq_str();
 
2919
  else if (unlikely(tv == uuid_time))
 
2920
  {
 
2921
    /* special protection from low-res system clocks */
 
2922
    nanoseq++;
 
2923
    tv++;
 
2924
  }
 
2925
  else
 
2926
  {
 
2927
    if (nanoseq)
 
2928
    {
 
2929
      tv-=nanoseq;
 
2930
      nanoseq=0;
 
2931
    }
 
2932
    assert(tv > uuid_time);
 
2933
  }
 
2934
  uuid_time=tv;
 
2935
  pthread_mutex_unlock(&LOCK_uuid_generator);
 
2936
 
 
2937
  uint32 time_low=            (uint32) (tv & 0xFFFFFFFF);
 
2938
  uint16 time_mid=            (uint16) ((tv >> 32) & 0xFFFF);
 
2939
  uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION);
 
2940
 
 
2941
  str->realloc(UUID_LENGTH+1);
 
2942
  str->length(UUID_LENGTH);
 
2943
  str->set_charset(system_charset_info);
 
2944
  s=(char *) str->ptr();
 
2945
  s[8]=s[13]='-';
 
2946
  tohex(s, time_low, 8);
 
2947
  tohex(s+9, time_mid, 4);
 
2948
  tohex(s+14, time_hi_and_version, 4);
 
2949
  strmov(s+18, clock_seq_and_node_str);
 
2950
  return str;
 
2951
}