mySQL 5.0.11 sources for tomato
[tomato.git] / release / src / router / mysql / sql / item_strfunc.cc
blob25473815b9c5725cd4b7d74c5eadd9c0e2772301
1 /*
2 Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 of the License.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 /**
19 @file
21 @brief
22 This file defines all string functions
24 @warning
25 Some string functions don't always put and end-null on a String.
26 (This shouldn't be needed)
29 #ifdef USE_PRAGMA_IMPLEMENTATION
30 #pragma implementation // gcc: Class implementation
31 #endif
33 #include "mysql_priv.h"
34 #include <m_ctype.h>
35 #include "my_md5.h"
36 #include "sha1.h"
37 #include "my_aes.h"
38 #include <zlib.h>
39 C_MODE_START
40 #include "../mysys/my_static.h" // For soundex_map
41 C_MODE_END
43 /**
44 @todo Remove this. It is not safe to use a shared String object.
46 String my_empty_string("",default_charset_info);
50 Convert an array of bytes to a hexadecimal representation.
52 Used to generate a hexadecimal representation of a message digest.
54 static void array_to_hex(char *to, const char *str, uint len)
56 const char *str_end= str + len;
57 for (; str != str_end; ++str)
59 *to++= _dig_vec_lower[((uchar) *str) >> 4];
60 *to++= _dig_vec_lower[((uchar) *str) & 0x0F];
65 bool Item_str_func::fix_fields(THD *thd, Item **ref)
67 bool res= Item_func::fix_fields(thd, ref);
69 In Item_str_func::check_well_formed_result() we may set null_value
70 flag on the same condition as in test() below.
72 maybe_null= (maybe_null ||
73 test(thd->variables.sql_mode &
74 (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)));
75 return res;
79 my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
81 DBUG_ASSERT(fixed == 1);
82 char buff[64];
83 String *res, tmp(buff,sizeof(buff), &my_charset_bin);
84 res= val_str(&tmp);
85 if (!res)
86 return 0;
87 (void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
88 res->length(), res->charset(), decimal_value);
89 return decimal_value;
93 double Item_str_func::val_real()
95 DBUG_ASSERT(fixed == 1);
96 int err_not_used;
97 char *end_not_used, buff[64];
98 String *res, tmp(buff,sizeof(buff), &my_charset_bin);
99 res= val_str(&tmp);
100 return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
101 &end_not_used, &err_not_used) : 0.0;
105 longlong Item_str_func::val_int()
107 DBUG_ASSERT(fixed == 1);
108 int err;
109 char buff[22];
110 String *res, tmp(buff,sizeof(buff), &my_charset_bin);
111 res= val_str(&tmp);
112 return (res ?
113 my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL,
114 &err) :
115 (longlong) 0);
119 String *Item_func_md5::val_str(String *str)
121 DBUG_ASSERT(fixed == 1);
122 String * sptr= args[0]->val_str(str);
123 str->set_charset(&my_charset_bin);
124 if (sptr)
126 uchar digest[16];
128 null_value=0;
129 MY_MD5_HASH(digest,(uchar *) sptr->ptr(), sptr->length());
130 if (str->alloc(32)) // Ensure that memory is free
132 null_value=1;
133 return 0;
135 array_to_hex((char *) str->ptr(), (const char*) digest, 16);
136 str->length((uint) 32);
137 return str;
139 null_value=1;
140 return 0;
144 void Item_func_md5::fix_length_and_dec()
146 max_length=32;
148 The MD5() function treats its parameter as being a case sensitive. Thus
149 we set binary collation on it so different instances of MD5() will be
150 compared properly.
152 args[0]->collation.set(
153 get_charset_by_csname(args[0]->collation.collation->csname,
154 MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
158 String *Item_func_sha::val_str(String *str)
160 DBUG_ASSERT(fixed == 1);
161 String * sptr= args[0]->val_str(str);
162 str->set_charset(&my_charset_bin);
163 if (sptr) /* If we got value different from NULL */
165 SHA1_CONTEXT context; /* Context used to generate SHA1 hash */
166 /* Temporary buffer to store 160bit digest */
167 uint8 digest[SHA1_HASH_SIZE];
168 mysql_sha1_reset(&context); /* We do not have to check for error here */
169 /* No need to check error as the only case would be too long message */
170 mysql_sha1_input(&context,
171 (const uchar *) sptr->ptr(), sptr->length());
172 /* Ensure that memory is free and we got result */
173 if (!( str->alloc(SHA1_HASH_SIZE*2) ||
174 (mysql_sha1_result(&context,digest))))
176 array_to_hex((char *) str->ptr(), (const char*) digest, SHA1_HASH_SIZE);
177 str->length((uint) SHA1_HASH_SIZE*2);
178 null_value=0;
179 return str;
182 null_value=1;
183 return 0;
186 void Item_func_sha::fix_length_and_dec()
188 max_length=SHA1_HASH_SIZE*2; // size of hex representation of hash
190 The SHA() function treats its parameter as being a case sensitive. Thus
191 we set binary collation on it so different instances of MD5() will be
192 compared properly.
194 args[0]->collation.set(
195 get_charset_by_csname(args[0]->collation.collation->csname,
196 MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
200 /* Implementation of AES encryption routines */
202 String *Item_func_aes_encrypt::val_str(String *str)
204 DBUG_ASSERT(fixed == 1);
205 char key_buff[80];
206 String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
207 String *sptr= args[0]->val_str(str); // String to encrypt
208 String *key= args[1]->val_str(&tmp_key_value); // key
209 int aes_length;
210 if (sptr && key) // we need both arguments to be not NULL
212 null_value=0;
213 aes_length=my_aes_get_size(sptr->length()); // Calculate result length
215 if (!str_value.alloc(aes_length)) // Ensure that memory is free
217 // finally encrypt directly to allocated buffer.
218 if (my_aes_encrypt(sptr->ptr(),sptr->length(), (char*) str_value.ptr(),
219 key->ptr(), key->length()) == aes_length)
221 // We got the expected result length
222 str_value.length((uint) aes_length);
223 return &str_value;
227 null_value=1;
228 return 0;
232 void Item_func_aes_encrypt::fix_length_and_dec()
234 max_length=my_aes_get_size(args[0]->max_length);
238 String *Item_func_aes_decrypt::val_str(String *str)
240 DBUG_ASSERT(fixed == 1);
241 char key_buff[80];
242 String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
243 String *sptr, *key;
244 DBUG_ENTER("Item_func_aes_decrypt::val_str");
246 sptr= args[0]->val_str(str); // String to decrypt
247 key= args[1]->val_str(&tmp_key_value); // Key
248 if (sptr && key) // Need to have both arguments not NULL
250 null_value=0;
251 if (!str_value.alloc(sptr->length())) // Ensure that memory is free
253 // finally decrypt directly to allocated buffer.
254 int length;
255 length=my_aes_decrypt(sptr->ptr(), sptr->length(),
256 (char*) str_value.ptr(),
257 key->ptr(), key->length());
258 if (length >= 0) // if we got correct data data
260 str_value.length((uint) length);
261 DBUG_RETURN(&str_value);
265 // Bad parameters. No memory or bad data will all go here
266 null_value=1;
267 DBUG_RETURN(0);
271 void Item_func_aes_decrypt::fix_length_and_dec()
273 max_length=args[0]->max_length;
274 maybe_null= 1;
279 Concatenate args with the following premises:
280 If only one arg (which is ok), return value of arg;
281 Don't reallocate val_str() if not absolute necessary.
284 String *Item_func_concat::val_str(String *str)
286 DBUG_ASSERT(fixed == 1);
287 String *res,*res2,*use_as_buff;
288 uint i;
289 bool is_const= 0;
291 null_value=0;
292 if (!(res=args[0]->val_str(str)))
293 goto null;
294 use_as_buff= &tmp_value;
295 /* Item_subselect in --ps-protocol mode will state it as a non-const */
296 is_const= args[0]->const_item() || !args[0]->used_tables();
297 for (i=1 ; i < arg_count ; i++)
299 if (res->length() == 0)
301 if (!(res=args[i]->val_str(str)))
302 goto null;
304 CONCAT accumulates its result in the result of its the first
305 non-empty argument. Because of this we need is_const to be
306 evaluated only for it.
308 is_const= args[i]->const_item() || !args[i]->used_tables();
310 else
312 if (!(res2=args[i]->val_str(use_as_buff)))
313 goto null;
314 if (res2->length() == 0)
315 continue;
316 if (res->length()+res2->length() >
317 current_thd->variables.max_allowed_packet)
319 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
320 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
321 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
322 current_thd->variables.max_allowed_packet);
323 goto null;
325 if (!is_const && res->alloced_length() >= res->length()+res2->length())
326 { // Use old buffer
327 res->append(*res2);
329 else if (str->alloced_length() >= res->length()+res2->length())
331 if (str->ptr() == res2->ptr())
332 str->replace(0,0,*res);
333 else
335 str->copy(*res);
336 str->append(*res2);
338 res= str;
339 use_as_buff= &tmp_value;
341 else if (res == &tmp_value)
343 if (res->append(*res2)) // Must be a blob
344 goto null;
346 else if (res2 == &tmp_value)
347 { // This can happend only 1 time
348 if (tmp_value.replace(0,0,*res))
349 goto null;
350 res= &tmp_value;
351 use_as_buff=str; // Put next arg here
353 else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
354 res2->ptr() <= tmp_value.ptr() + tmp_value.alloced_length())
357 This happens really seldom:
358 In this case res2 is sub string of tmp_value. We will
359 now work in place in tmp_value to set it to res | res2
361 /* Chop the last characters in tmp_value that isn't in res2 */
362 tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
363 res2->length());
364 /* Place res2 at start of tmp_value, remove chars before res2 */
365 if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
366 *res))
367 goto null;
368 res= &tmp_value;
369 use_as_buff=str; // Put next arg here
371 else
372 { // Two big const strings
374 NOTE: We should be prudent in the initial allocation unit -- the
375 size of the arguments is a function of data distribution, which
376 can be any. Instead of overcommitting at the first row, we grow
377 the allocated amount by the factor of 2. This ensures that no
378 more than 25% of memory will be overcommitted on average.
381 uint concat_len= res->length() + res2->length();
383 if (tmp_value.alloced_length() < concat_len)
385 if (tmp_value.alloced_length() == 0)
387 if (tmp_value.alloc(concat_len))
388 goto null;
390 else
392 uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
394 if (tmp_value.realloc(new_len))
395 goto null;
399 if (tmp_value.copy(*res) || tmp_value.append(*res2))
400 goto null;
402 res= &tmp_value;
403 use_as_buff=str;
405 is_const= 0;
408 res->set_charset(collation.collation);
409 return res;
411 null:
412 null_value=1;
413 return 0;
417 void Item_func_concat::fix_length_and_dec()
419 ulonglong max_result_length= 0;
421 if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
422 return;
424 for (uint i=0 ; i < arg_count ; i++)
426 if (args[i]->collation.collation->mbmaxlen != collation.collation->mbmaxlen)
427 max_result_length+= (args[i]->max_length /
428 args[i]->collation.collation->mbmaxlen) *
429 collation.collation->mbmaxlen;
430 else
431 max_result_length+= args[i]->max_length;
434 if (max_result_length >= MAX_BLOB_WIDTH)
436 max_result_length= MAX_BLOB_WIDTH;
437 maybe_null= 1;
439 max_length= (ulong) max_result_length;
443 @details
444 Function des_encrypt() by tonu@spam.ee & monty
445 Works only if compiled with OpenSSL library support.
446 @return
447 A binary string where first character is CHAR(128 | key-number).
448 If one uses a string key key_number is 127.
449 Encryption result is longer than original by formula:
450 @code new_length= org_length + (8-(org_length % 8))+1 @endcode
453 String *Item_func_des_encrypt::val_str(String *str)
455 DBUG_ASSERT(fixed == 1);
456 #ifdef HAVE_OPENSSL
457 uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
458 DES_cblock ivec;
459 struct st_des_keyblock keyblock;
460 struct st_des_keyschedule keyschedule;
461 const char *append_str="********";
462 uint key_number, res_length, tail;
463 String *res= args[0]->val_str(str);
465 if ((null_value= args[0]->null_value))
466 return 0; // ENCRYPT(NULL) == NULL
467 if ((res_length=res->length()) == 0)
468 return make_empty_result();
470 if (arg_count == 1)
472 /* Protect against someone doing FLUSH DES_KEY_FILE */
473 VOID(pthread_mutex_lock(&LOCK_des_key_file));
474 keyschedule= des_keyschedule[key_number=des_default_key];
475 VOID(pthread_mutex_unlock(&LOCK_des_key_file));
477 else if (args[1]->result_type() == INT_RESULT)
479 key_number= (uint) args[1]->val_int();
480 if (key_number > 9)
481 goto error;
482 VOID(pthread_mutex_lock(&LOCK_des_key_file));
483 keyschedule= des_keyschedule[key_number];
484 VOID(pthread_mutex_unlock(&LOCK_des_key_file));
486 else
488 String *keystr=args[1]->val_str(&tmp_value);
489 if (!keystr)
490 goto error;
491 key_number=127; // User key string
493 /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */
494 bzero((char*) &ivec,sizeof(ivec));
495 EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
496 (uchar*) keystr->ptr(), (int) keystr->length(),
497 1, (uchar*) &keyblock,ivec);
498 DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
499 DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
500 DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
504 The problem: DES algorithm requires original data to be in 8-bytes
505 chunks. Missing bytes get filled with '*'s and result of encryption
506 can be up to 8 bytes longer than original string. When decrypted,
507 we do not know the size of original string :(
508 We add one byte with value 0x1..0x8 as the last byte of the padded
509 string marking change of string length.
512 tail= 8 - (res_length % 8); // 1..8 marking extra length
513 res_length+=tail;
514 tmp_arg.realloc(res_length);
515 tmp_arg.length(0);
516 tmp_arg.append(res->ptr(), res->length());
517 code= ER_OUT_OF_RESOURCES;
518 if (tmp_arg.append(append_str, tail) || tmp_value.alloc(res_length+1))
519 goto error;
520 tmp_arg[res_length-1]=tail; // save extra length
521 tmp_value.realloc(res_length+1);
522 tmp_value.length(res_length+1);
523 tmp_value.set_charset(&my_charset_bin);
524 tmp_value[0]=(char) (128 | key_number);
525 // Real encryption
526 bzero((char*) &ivec,sizeof(ivec));
527 DES_ede3_cbc_encrypt((const uchar*) (tmp_arg.ptr()),
528 (uchar*) (tmp_value.ptr()+1),
529 res_length,
530 &keyschedule.ks1,
531 &keyschedule.ks2,
532 &keyschedule.ks3,
533 &ivec, TRUE);
534 return &tmp_value;
536 error:
537 push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
538 code, ER(code),
539 "des_encrypt");
540 #else
541 push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
542 ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
543 "des_encrypt","--with-openssl");
544 #endif /* HAVE_OPENSSL */
545 null_value=1;
546 return 0;
550 String *Item_func_des_decrypt::val_str(String *str)
552 DBUG_ASSERT(fixed == 1);
553 #ifdef HAVE_OPENSSL
554 uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
555 DES_cblock ivec;
556 struct st_des_keyblock keyblock;
557 struct st_des_keyschedule keyschedule;
558 String *res= args[0]->val_str(str);
559 uint length,tail;
561 if ((null_value= args[0]->null_value))
562 return 0;
563 length= res->length();
564 if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128))
565 return res; // Skip decryption if not encrypted
567 if (arg_count == 1) // If automatic uncompression
569 uint key_number=(uint) (*res)[0] & 127;
570 // Check if automatic key and that we have privilege to uncompress using it
571 if (!(current_thd->security_ctx->master_access & SUPER_ACL) ||
572 key_number > 9)
573 goto error;
575 VOID(pthread_mutex_lock(&LOCK_des_key_file));
576 keyschedule= des_keyschedule[key_number];
577 VOID(pthread_mutex_unlock(&LOCK_des_key_file));
579 else
581 // We make good 24-byte (168 bit) key from given plaintext key with MD5
582 String *keystr=args[1]->val_str(&tmp_value);
583 if (!keystr)
584 goto error;
586 bzero((char*) &ivec,sizeof(ivec));
587 EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
588 (uchar*) keystr->ptr(),(int) keystr->length(),
589 1,(uchar*) &keyblock,ivec);
590 // Here we set all 64-bit keys (56 effective) one by one
591 DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
592 DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
593 DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
595 code= ER_OUT_OF_RESOURCES;
596 if (tmp_value.alloc(length-1))
597 goto error;
599 bzero((char*) &ivec,sizeof(ivec));
600 DES_ede3_cbc_encrypt((const uchar*) res->ptr()+1,
601 (uchar*) (tmp_value.ptr()),
602 length-1,
603 &keyschedule.ks1,
604 &keyschedule.ks2,
605 &keyschedule.ks3,
606 &ivec, FALSE);
607 /* Restore old length of key */
608 if ((tail=(uint) (uchar) tmp_value[length-2]) > 8)
609 goto wrong_key; // Wrong key
610 tmp_value.length(length-1-tail);
611 tmp_value.set_charset(&my_charset_bin);
612 return &tmp_value;
614 error:
615 push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
616 code, ER(code),
617 "des_decrypt");
618 wrong_key:
619 #else
620 push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
621 ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
622 "des_decrypt","--with-openssl");
623 #endif /* HAVE_OPENSSL */
624 null_value=1;
625 return 0;
630 concat with separator. First arg is the separator
631 concat_ws takes at least two arguments.
634 String *Item_func_concat_ws::val_str(String *str)
636 DBUG_ASSERT(fixed == 1);
637 char tmp_str_buff[10];
638 String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
639 *sep_str, *res, *res2,*use_as_buff;
640 uint i;
641 bool is_const= 0;
643 null_value=0;
644 if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
645 goto null;
647 use_as_buff= &tmp_value;
648 str->length(0); // QQ; Should be removed
649 res=str;
651 // Skip until non-null argument is found.
652 // If not, return the empty string
653 for (i=1; i < arg_count; i++)
654 if ((res= args[i]->val_str(str)))
656 is_const= args[i]->const_item() || !args[i]->used_tables();
657 break;
660 if (i == arg_count)
661 return make_empty_result();
663 for (i++; i < arg_count ; i++)
665 if (!(res2= args[i]->val_str(use_as_buff)))
666 continue; // Skip NULL
668 if (res->length() + sep_str->length() + res2->length() >
669 current_thd->variables.max_allowed_packet)
671 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
672 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
673 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
674 current_thd->variables.max_allowed_packet);
675 goto null;
677 if (!is_const && res->alloced_length() >=
678 res->length() + sep_str->length() + res2->length())
679 { // Use old buffer
680 res->append(*sep_str); // res->length() > 0 always
681 res->append(*res2);
683 else if (str->alloced_length() >=
684 res->length() + sep_str->length() + res2->length())
686 /* We have room in str; We can't get any errors here */
687 if (str->ptr() == res2->ptr())
688 { // This is quite uncommon!
689 str->replace(0,0,*sep_str);
690 str->replace(0,0,*res);
692 else
694 str->copy(*res);
695 str->append(*sep_str);
696 str->append(*res2);
698 res=str;
699 use_as_buff= &tmp_value;
701 else if (res == &tmp_value)
703 if (res->append(*sep_str) || res->append(*res2))
704 goto null; // Must be a blob
706 else if (res2 == &tmp_value)
707 { // This can happend only 1 time
708 if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res))
709 goto null;
710 res= &tmp_value;
711 use_as_buff=str; // Put next arg here
713 else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
714 res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
717 This happens really seldom:
718 In this case res2 is sub string of tmp_value. We will
719 now work in place in tmp_value to set it to res | sep_str | res2
721 /* Chop the last characters in tmp_value that isn't in res2 */
722 tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
723 res2->length());
724 /* Place res2 at start of tmp_value, remove chars before res2 */
725 if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
726 *res) ||
727 tmp_value.replace(res->length(),0, *sep_str))
728 goto null;
729 res= &tmp_value;
730 use_as_buff=str; // Put next arg here
732 else
733 { // Two big const strings
735 NOTE: We should be prudent in the initial allocation unit -- the
736 size of the arguments is a function of data distribution, which can
737 be any. Instead of overcommitting at the first row, we grow the
738 allocated amount by the factor of 2. This ensures that no more than
739 25% of memory will be overcommitted on average.
742 uint concat_len= res->length() + sep_str->length() + res2->length();
744 if (tmp_value.alloced_length() < concat_len)
746 if (tmp_value.alloced_length() == 0)
748 if (tmp_value.alloc(concat_len))
749 goto null;
751 else
753 uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
755 if (tmp_value.realloc(new_len))
756 goto null;
760 if (tmp_value.copy(*res) ||
761 tmp_value.append(*sep_str) ||
762 tmp_value.append(*res2))
763 goto null;
764 res= &tmp_value;
765 use_as_buff=str;
768 res->set_charset(collation.collation);
769 return res;
771 null:
772 null_value=1;
773 return 0;
777 void Item_func_concat_ws::fix_length_and_dec()
779 ulonglong max_result_length;
781 if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
782 return;
785 arg_count cannot be less than 2,
786 it is done on parser level in sql_yacc.yy
787 so, (arg_count - 2) is safe here.
789 max_result_length= (ulonglong) args[0]->max_length * (arg_count - 2);
790 for (uint i=1 ; i < arg_count ; i++)
791 max_result_length+=args[i]->max_length;
793 if (max_result_length >= MAX_BLOB_WIDTH)
795 max_result_length= MAX_BLOB_WIDTH;
796 maybe_null= 1;
798 max_length= (ulong) max_result_length;
802 String *Item_func_reverse::val_str(String *str)
804 DBUG_ASSERT(fixed == 1);
805 String *res = args[0]->val_str(str);
806 char *ptr, *end, *tmp;
808 if ((null_value=args[0]->null_value))
809 return 0;
810 /* An empty string is a special case as the string pointer may be null */
811 if (!res->length())
812 return make_empty_result();
813 if (tmp_value.alloced_length() < res->length() &&
814 tmp_value.realloc(res->length()))
816 null_value= 1;
817 return 0;
819 tmp_value.length(res->length());
820 tmp_value.set_charset(res->charset());
821 ptr= (char *) res->ptr();
822 end= ptr + res->length();
823 tmp= (char *) tmp_value.ptr() + tmp_value.length();
824 #ifdef USE_MB
825 if (use_mb(res->charset()))
827 register uint32 l;
828 while (ptr < end)
830 if ((l= my_ismbchar(res->charset(),ptr,end)))
832 tmp-= l;
833 memcpy(tmp,ptr,l);
834 ptr+= l;
836 else
837 *--tmp= *ptr++;
840 else
841 #endif /* USE_MB */
843 while (ptr < end)
844 *--tmp= *ptr++;
846 return &tmp_value;
850 void Item_func_reverse::fix_length_and_dec()
852 collation.set(args[0]->collation);
853 max_length = args[0]->max_length;
857 Replace all occurences of string2 in string1 with string3.
859 Don't reallocate val_str() if not needed.
861 @todo
862 Fix that this works with binary strings when using USE_MB
865 String *Item_func_replace::val_str(String *str)
867 DBUG_ASSERT(fixed == 1);
868 String *res,*res2,*res3;
869 int offset;
870 uint from_length,to_length;
871 bool alloced=0;
872 #ifdef USE_MB
873 const char *ptr,*end,*strend,*search,*search_end;
874 register uint32 l;
875 bool binary_cmp;
876 #endif
878 null_value=0;
879 res=args[0]->val_str(str);
880 if (args[0]->null_value)
881 goto null;
882 res2=args[1]->val_str(&tmp_value);
883 if (args[1]->null_value)
884 goto null;
886 res->set_charset(collation.collation);
888 #ifdef USE_MB
889 binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
890 #endif
892 if (res2->length() == 0)
893 return res;
894 #ifndef USE_MB
895 if ((offset=res->strstr(*res2)) < 0)
896 return res;
897 #else
898 offset=0;
899 if (binary_cmp && (offset=res->strstr(*res2)) < 0)
900 return res;
901 #endif
902 if (!(res3=args[2]->val_str(&tmp_value2)))
903 goto null;
904 from_length= res2->length();
905 to_length= res3->length();
907 #ifdef USE_MB
908 if (!binary_cmp)
910 search=res2->ptr();
911 search_end=search+from_length;
912 redo:
913 DBUG_ASSERT(res->ptr() || !offset);
914 ptr=res->ptr()+offset;
915 strend=res->ptr()+res->length();
917 In some cases val_str() can return empty string
918 with ptr() == NULL and length() == 0.
919 Let's check strend to avoid overflow.
921 end= strend ? strend - from_length + 1 : NULL;
922 while (ptr < end)
924 if (*ptr == *search)
926 register char *i,*j;
927 i=(char*) ptr+1; j=(char*) search+1;
928 while (j != search_end)
929 if (*i++ != *j++) goto skip;
930 offset= (int) (ptr-res->ptr());
931 if (res->length()-from_length + to_length >
932 current_thd->variables.max_allowed_packet)
934 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
935 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
936 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
937 func_name(),
938 current_thd->variables.max_allowed_packet);
940 goto null;
942 if (!alloced)
944 alloced=1;
945 res=copy_if_not_alloced(str,res,res->length()+to_length);
947 res->replace((uint) offset,from_length,*res3);
948 offset+=(int) to_length;
949 goto redo;
951 skip:
952 if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
953 else ++ptr;
956 else
957 #endif /* USE_MB */
960 if (res->length()-from_length + to_length >
961 current_thd->variables.max_allowed_packet)
963 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
964 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
965 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
966 current_thd->variables.max_allowed_packet);
967 goto null;
969 if (!alloced)
971 alloced=1;
972 res=copy_if_not_alloced(str,res,res->length()+to_length);
974 res->replace((uint) offset,from_length,*res3);
975 offset+=(int) to_length;
977 while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
978 return res;
980 null:
981 null_value=1;
982 return 0;
986 void Item_func_replace::fix_length_and_dec()
988 ulonglong max_result_length= args[0]->max_length;
989 int diff=(int) (args[2]->max_length - args[1]->max_length);
990 if (diff > 0 && args[1]->max_length)
991 { // Calculate of maxreplaces
992 ulonglong max_substrs= max_result_length/args[1]->max_length;
993 max_result_length+= max_substrs * (uint) diff;
995 if (max_result_length >= MAX_BLOB_WIDTH)
997 max_result_length= MAX_BLOB_WIDTH;
998 maybe_null= 1;
1000 max_length= (ulong) max_result_length;
1002 if (agg_arg_charsets(collation, args, 3, MY_COLL_CMP_CONV, 1))
1003 return;
1007 String *Item_func_insert::val_str(String *str)
1009 DBUG_ASSERT(fixed == 1);
1010 String *res,*res2;
1011 longlong start, length; /* must be longlong to avoid truncation */
1013 null_value=0;
1014 res=args[0]->val_str(str);
1015 res2=args[3]->val_str(&tmp_value);
1016 start= args[1]->val_int() - 1;
1017 length= args[2]->val_int();
1019 if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
1020 args[3]->null_value)
1021 goto null; /* purecov: inspected */
1023 if ((start < 0) || (start > res->length()))
1024 return res; // Wrong param; skip insert
1025 if ((length < 0) || (length > res->length()))
1026 length= res->length();
1029 There is one exception not handled (intentionaly) by the character set
1030 aggregation code. If one string is strong side and is binary, and
1031 another one is weak side and is a multi-byte character string,
1032 then we need to operate on the second string in terms on bytes when
1033 calling ::numchars() and ::charpos(), rather than in terms of characters.
1034 Lets substitute its character set to binary.
1036 if (collation.collation == &my_charset_bin)
1038 res->set_charset(&my_charset_bin);
1039 res2->set_charset(&my_charset_bin);
1042 /* start and length are now sufficiently valid to pass to charpos function */
1043 start= res->charpos((int) start);
1044 length= res->charpos((int) length, (uint32) start);
1046 /* Re-testing with corrected params */
1047 if (start > res->length())
1048 return res; /* purecov: inspected */ // Wrong param; skip insert
1049 if (length > res->length() - start)
1050 length= res->length() - start;
1052 if ((ulonglong) (res->length() - length + res2->length()) >
1053 (ulonglong) current_thd->variables.max_allowed_packet)
1055 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
1056 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1057 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1058 func_name(), current_thd->variables.max_allowed_packet);
1059 goto null;
1061 res=copy_if_not_alloced(str,res,res->length());
1062 res->replace((uint32) start,(uint32) length,*res2);
1063 return res;
1064 null:
1065 null_value=1;
1066 return 0;
1070 void Item_func_insert::fix_length_and_dec()
1072 ulonglong max_result_length;
1074 // Handle character set for args[0] and args[3].
1075 if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 3))
1076 return;
1077 max_result_length= ((ulonglong) args[0]->max_length+
1078 (ulonglong) args[3]->max_length);
1079 if (max_result_length >= MAX_BLOB_WIDTH)
1081 max_result_length= MAX_BLOB_WIDTH;
1082 maybe_null= 1;
1084 max_length= (ulong) max_result_length;
1088 String *Item_str_conv::val_str(String *str)
1090 DBUG_ASSERT(fixed == 1);
1091 String *res;
1092 if (!(res=args[0]->val_str(str)))
1094 null_value=1; /* purecov: inspected */
1095 return 0; /* purecov: inspected */
1097 null_value=0;
1098 if (multiply == 1)
1100 uint len;
1101 res= copy_if_not_alloced(str,res,res->length());
1102 len= converter(collation.collation, (char*) res->ptr(), res->length(),
1103 (char*) res->ptr(), res->length());
1104 DBUG_ASSERT(len <= res->length());
1105 res->length(len);
1107 else
1109 uint len= res->length() * multiply;
1110 tmp_value.alloc(len);
1111 tmp_value.set_charset(collation.collation);
1112 len= converter(collation.collation, (char*) res->ptr(), res->length(),
1113 (char*) tmp_value.ptr(), len);
1114 tmp_value.length(len);
1115 res= &tmp_value;
1117 return res;
1121 void Item_func_lcase::fix_length_and_dec()
1123 collation.set(args[0]->collation);
1124 multiply= collation.collation->casedn_multiply;
1125 converter= collation.collation->cset->casedn;
1126 max_length= args[0]->max_length * multiply;
1129 void Item_func_ucase::fix_length_and_dec()
1131 collation.set(args[0]->collation);
1132 multiply= collation.collation->caseup_multiply;
1133 converter= collation.collation->cset->caseup;
1134 max_length= args[0]->max_length * multiply;
1138 String *Item_func_left::val_str(String *str)
1140 DBUG_ASSERT(fixed == 1);
1141 String *res= args[0]->val_str(str);
1143 /* must be longlong to avoid truncation */
1144 longlong length= args[1]->val_int();
1145 uint char_pos;
1147 if ((null_value=(args[0]->null_value || args[1]->null_value)))
1148 return 0;
1150 /* if "unsigned_flag" is set, we have a *huge* positive number. */
1151 if ((length <= 0) && (!args[1]->unsigned_flag))
1152 return make_empty_result();
1153 if ((res->length() <= (ulonglong) length) ||
1154 (res->length() <= (char_pos= res->charpos((int) length))))
1155 return res;
1157 tmp_value.set(*res, 0, char_pos);
1158 return &tmp_value;
1162 void Item_str_func::left_right_max_length()
1164 max_length=args[0]->max_length;
1165 if (args[1]->const_item())
1167 int length=(int) args[1]->val_int()*collation.collation->mbmaxlen;
1168 if (length <= 0)
1169 max_length=0;
1170 else
1171 set_if_smaller(max_length,(uint) length);
1176 void Item_func_left::fix_length_and_dec()
1178 collation.set(args[0]->collation);
1179 left_right_max_length();
1183 String *Item_func_right::val_str(String *str)
1185 DBUG_ASSERT(fixed == 1);
1186 String *res= args[0]->val_str(str);
1187 /* must be longlong to avoid truncation */
1188 longlong length= args[1]->val_int();
1190 if ((null_value=(args[0]->null_value || args[1]->null_value)))
1191 return 0; /* purecov: inspected */
1193 /* if "unsigned_flag" is set, we have a *huge* positive number. */
1194 if ((length <= 0) && (!args[1]->unsigned_flag))
1195 return make_empty_result(); /* purecov: inspected */
1197 if (res->length() <= (ulonglong) length)
1198 return res; /* purecov: inspected */
1200 uint start=res->numchars();
1201 if (start <= (uint) length)
1202 return res;
1203 start=res->charpos(start - (uint) length);
1204 tmp_value.set(*res,start,res->length()-start);
1205 return &tmp_value;
1209 void Item_func_right::fix_length_and_dec()
1211 collation.set(args[0]->collation);
1212 left_right_max_length();
1216 String *Item_func_substr::val_str(String *str)
1218 DBUG_ASSERT(fixed == 1);
1219 String *res = args[0]->val_str(str);
1220 /* must be longlong to avoid truncation */
1221 longlong start= args[1]->val_int();
1222 /* Assumes that the maximum length of a String is < INT_MAX32. */
1223 /* Limit so that code sees out-of-bound value properly. */
1224 longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
1225 longlong tmp_length;
1227 if ((null_value=(args[0]->null_value || args[1]->null_value ||
1228 (arg_count == 3 && args[2]->null_value))))
1229 return 0; /* purecov: inspected */
1231 /* Negative or zero length, will return empty string. */
1232 if ((arg_count == 3) && (length <= 0) &&
1233 (length == 0 || !args[2]->unsigned_flag))
1234 return make_empty_result();
1236 /* Assumes that the maximum length of a String is < INT_MAX32. */
1237 /* Set here so that rest of code sees out-of-bound value as such. */
1238 if ((length <= 0) || (length > INT_MAX32))
1239 length= INT_MAX32;
1241 /* if "unsigned_flag" is set, we have a *huge* positive number. */
1242 /* Assumes that the maximum length of a String is < INT_MAX32. */
1243 if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
1244 (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
1245 return make_empty_result();
1247 start= ((start < 0) ? res->numchars() + start : start - 1);
1248 start= res->charpos((int) start);
1249 if ((start < 0) || ((uint) start + 1 > res->length()))
1250 return make_empty_result();
1252 length= res->charpos((int) length, (uint32) start);
1253 tmp_length= res->length() - start;
1254 length= min(length, tmp_length);
1256 if (!start && (longlong) res->length() == length)
1257 return res;
1258 tmp_value.set(*res, (uint32) start, (uint32) length);
1259 return &tmp_value;
1263 void Item_func_substr::fix_length_and_dec()
1265 max_length=args[0]->max_length;
1267 collation.set(args[0]->collation);
1268 if (args[1]->const_item())
1270 int32 start= (int32) args[1]->val_int();
1271 if (start < 0)
1272 max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start);
1273 else
1274 max_length-= min((uint)(start - 1), max_length);
1276 if (arg_count == 3 && args[2]->const_item())
1278 int32 length= (int32) args[2]->val_int();
1279 if (length <= 0)
1280 max_length=0; /* purecov: inspected */
1281 else
1282 set_if_smaller(max_length,(uint) length);
1284 max_length*= collation.collation->mbmaxlen;
1288 void Item_func_substr_index::fix_length_and_dec()
1290 max_length= args[0]->max_length;
1292 if (agg_arg_charsets(collation, args, 2, MY_COLL_CMP_CONV, 1))
1293 return;
1297 String *Item_func_substr_index::val_str(String *str)
1299 DBUG_ASSERT(fixed == 1);
1300 String *res= args[0]->val_str(str);
1301 String *delimiter= args[1]->val_str(&tmp_value);
1302 int32 count= (int32) args[2]->val_int();
1303 uint offset;
1305 if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
1306 { // string and/or delim are null
1307 null_value=1;
1308 return 0;
1310 null_value=0;
1311 uint delimiter_length= delimiter->length();
1312 if (!res->length() || !delimiter_length || !count)
1313 return make_empty_result(); // Wrong parameters
1315 res->set_charset(collation.collation);
1317 #ifdef USE_MB
1318 if (use_mb(res->charset()))
1320 const char *ptr= res->ptr();
1321 const char *strend= ptr+res->length();
1322 const char *end= strend-delimiter_length+1;
1323 const char *search= delimiter->ptr();
1324 const char *search_end= search+delimiter_length;
1325 int32 n=0,c=count,pass;
1326 register uint32 l;
1327 for (pass=(count>0);pass<2;++pass)
1329 while (ptr < end)
1331 if (*ptr == *search)
1333 register char *i,*j;
1334 i=(char*) ptr+1; j=(char*) search+1;
1335 while (j != search_end)
1336 if (*i++ != *j++) goto skip;
1337 if (pass==0) ++n;
1338 else if (!--c) break;
1339 ptr+= delimiter_length;
1340 continue;
1342 skip:
1343 if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
1344 else ++ptr;
1345 } /* either not found or got total number when count<0 */
1346 if (pass == 0) /* count<0 */
1348 c+=n+1;
1349 if (c<=0) return res; /* not found, return original string */
1350 ptr=res->ptr();
1352 else
1354 if (c) return res; /* Not found, return original string */
1355 if (count>0) /* return left part */
1357 tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
1359 else /* return right part */
1361 ptr+= delimiter_length;
1362 tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
1367 else
1368 #endif /* USE_MB */
1370 if (count > 0)
1371 { // start counting from the beginning
1372 for (offset=0; ; offset+= delimiter_length)
1374 if ((int) (offset= res->strstr(*delimiter, offset)) < 0)
1375 return res; // Didn't find, return org string
1376 if (!--count)
1378 tmp_value.set(*res,0,offset);
1379 break;
1383 else
1386 Negative index, start counting at the end
1388 for (offset=res->length(); offset ;)
1391 this call will result in finding the position pointing to one
1392 address space less than where the found substring is located
1393 in res
1395 if ((int) (offset= res->strrstr(*delimiter, offset)) < 0)
1396 return res; // Didn't find, return org string
1398 At this point, we've searched for the substring
1399 the number of times as supplied by the index value
1401 if (!++count)
1403 offset+= delimiter_length;
1404 tmp_value.set(*res,offset,res->length()- offset);
1405 break;
1411 We always mark tmp_value as const so that if val_str() is called again
1412 on this object, we don't disrupt the contents of tmp_value when it was
1413 derived from another String.
1415 tmp_value.mark_as_const();
1416 return (&tmp_value);
1420 ** The trim functions are extension to ANSI SQL because they trim substrings
1421 ** They ltrim() and rtrim() functions are optimized for 1 byte strings
1422 ** They also return the original string if possible, else they return
1423 ** a substring that points at the original string.
1427 String *Item_func_ltrim::val_str(String *str)
1429 DBUG_ASSERT(fixed == 1);
1430 char buff[MAX_FIELD_WIDTH], *ptr, *end;
1431 String tmp(buff,sizeof(buff),system_charset_info);
1432 String *res, *remove_str;
1433 uint remove_length;
1434 LINT_INIT(remove_length);
1436 res= args[0]->val_str(str);
1437 if ((null_value=args[0]->null_value))
1438 return 0;
1439 remove_str= &remove; /* Default value. */
1440 if (arg_count == 2)
1442 remove_str= args[1]->val_str(&tmp);
1443 if ((null_value= args[1]->null_value))
1444 return 0;
1447 if ((remove_length= remove_str->length()) == 0 ||
1448 remove_length > res->length())
1449 return res;
1451 ptr= (char*) res->ptr();
1452 end= ptr+res->length();
1453 if (remove_length == 1)
1455 char chr=(*remove_str)[0];
1456 while (ptr != end && *ptr == chr)
1457 ptr++;
1459 else
1461 const char *r_ptr=remove_str->ptr();
1462 end-=remove_length;
1463 while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
1464 ptr+=remove_length;
1465 end+=remove_length;
1467 if (ptr == res->ptr())
1468 return res;
1469 tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1470 return &tmp_value;
1474 String *Item_func_rtrim::val_str(String *str)
1476 DBUG_ASSERT(fixed == 1);
1477 char buff[MAX_FIELD_WIDTH], *ptr, *end;
1478 String tmp(buff, sizeof(buff), system_charset_info);
1479 String *res, *remove_str;
1480 uint remove_length;
1481 LINT_INIT(remove_length);
1483 res= args[0]->val_str(str);
1484 if ((null_value=args[0]->null_value))
1485 return 0;
1486 remove_str= &remove; /* Default value. */
1487 if (arg_count == 2)
1489 remove_str= args[1]->val_str(&tmp);
1490 if ((null_value= args[1]->null_value))
1491 return 0;
1494 if ((remove_length= remove_str->length()) == 0 ||
1495 remove_length > res->length())
1496 return res;
1498 ptr= (char*) res->ptr();
1499 end= ptr+res->length();
1500 #ifdef USE_MB
1501 char *p=ptr;
1502 register uint32 l;
1503 #endif
1504 if (remove_length == 1)
1506 char chr=(*remove_str)[0];
1507 #ifdef USE_MB
1508 if (use_mb(res->charset()))
1510 while (ptr < end)
1512 if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr;
1513 else ++ptr;
1515 ptr=p;
1517 #endif
1518 while (ptr != end && end[-1] == chr)
1519 end--;
1521 else
1523 const char *r_ptr=remove_str->ptr();
1524 #ifdef USE_MB
1525 if (use_mb(res->charset()))
1527 loop:
1528 while (ptr + remove_length < end)
1530 if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
1531 else ++ptr;
1533 if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1535 end-=remove_length;
1536 ptr=p;
1537 goto loop;
1540 else
1541 #endif /* USE_MB */
1543 while (ptr + remove_length <= end &&
1544 !memcmp(end-remove_length, r_ptr, remove_length))
1545 end-=remove_length;
1548 if (end == res->ptr()+res->length())
1549 return res;
1550 tmp_value.set(*res,0,(uint) (end-res->ptr()));
1551 return &tmp_value;
1555 String *Item_func_trim::val_str(String *str)
1557 DBUG_ASSERT(fixed == 1);
1558 char buff[MAX_FIELD_WIDTH], *ptr, *end;
1559 const char *r_ptr;
1560 String tmp(buff, sizeof(buff), system_charset_info);
1561 String *res, *remove_str;
1562 uint remove_length;
1563 LINT_INIT(remove_length);
1565 res= args[0]->val_str(str);
1566 if ((null_value=args[0]->null_value))
1567 return 0;
1568 remove_str= &remove; /* Default value. */
1569 if (arg_count == 2)
1571 remove_str= args[1]->val_str(&tmp);
1572 if ((null_value= args[1]->null_value))
1573 return 0;
1576 if ((remove_length= remove_str->length()) == 0 ||
1577 remove_length > res->length())
1578 return res;
1580 ptr= (char*) res->ptr();
1581 end= ptr+res->length();
1582 r_ptr= remove_str->ptr();
1583 while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
1584 ptr+=remove_length;
1585 #ifdef USE_MB
1586 if (use_mb(res->charset()))
1588 char *p=ptr;
1589 register uint32 l;
1590 loop:
1591 while (ptr + remove_length < end)
1593 if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
1594 else ++ptr;
1596 if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1598 end-=remove_length;
1599 ptr=p;
1600 goto loop;
1602 ptr=p;
1604 else
1605 #endif /* USE_MB */
1607 while (ptr + remove_length <= end &&
1608 !memcmp(end-remove_length,r_ptr,remove_length))
1609 end-=remove_length;
1611 if (ptr == res->ptr() && end == ptr+res->length())
1612 return res;
1613 tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1614 return &tmp_value;
1617 void Item_func_trim::fix_length_and_dec()
1619 max_length= args[0]->max_length;
1620 if (arg_count == 1)
1622 collation.set(args[0]->collation);
1623 remove.set_charset(collation.collation);
1624 remove.set_ascii(" ",1);
1626 else
1628 // Handle character set for args[1] and args[0].
1629 // Note that we pass args[1] as the first item, and args[0] as the second.
1630 if (agg_arg_charsets(collation, &args[1], 2, MY_COLL_CMP_CONV, -1))
1631 return;
1635 void Item_func_trim::print(String *str, enum_query_type query_type)
1637 if (arg_count == 1)
1639 Item_func::print(str, query_type);
1640 return;
1642 str->append(Item_func_trim::func_name());
1643 str->append('(');
1644 str->append(mode_name());
1645 str->append(' ');
1646 args[1]->print(str, query_type);
1647 str->append(STRING_WITH_LEN(" from "));
1648 args[0]->print(str, query_type);
1649 str->append(')');
1653 /* Item_func_password */
1655 String *Item_func_password::val_str(String *str)
1657 DBUG_ASSERT(fixed == 1);
1658 String *res= args[0]->val_str(str);
1659 if ((null_value=args[0]->null_value))
1660 return 0;
1661 if (res->length() == 0)
1662 return make_empty_result();
1663 my_make_scrambled_password(tmp_value, res->ptr(), res->length());
1664 str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, res->charset());
1665 return str;
1668 char *Item_func_password::alloc(THD *thd, const char *password,
1669 size_t pass_len)
1671 char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH+1);
1672 if (buff)
1673 my_make_scrambled_password(buff, password, pass_len);
1674 return buff;
1677 /* Item_func_old_password */
1679 String *Item_func_old_password::val_str(String *str)
1681 DBUG_ASSERT(fixed == 1);
1682 String *res= args[0]->val_str(str);
1683 if ((null_value=args[0]->null_value))
1684 return 0;
1685 if (res->length() == 0)
1686 return make_empty_result();
1687 my_make_scrambled_password_323(tmp_value, res->ptr(), res->length());
1688 str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, res->charset());
1689 return str;
1692 char *Item_func_old_password::alloc(THD *thd, const char *password,
1693 size_t pass_len)
1695 char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1);
1696 if (buff)
1697 my_make_scrambled_password_323(buff, password, pass_len);
1698 return buff;
1702 #define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
1704 String *Item_func_encrypt::val_str(String *str)
1706 DBUG_ASSERT(fixed == 1);
1707 String *res =args[0]->val_str(str);
1709 #ifdef HAVE_CRYPT
1710 char salt[3],*salt_ptr;
1711 if ((null_value=args[0]->null_value))
1712 return 0;
1713 if (res->length() == 0)
1714 return make_empty_result();
1715 if (arg_count == 1)
1716 { // generate random salt
1717 time_t timestamp=current_thd->query_start();
1718 salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
1719 salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
1720 salt[2] = 0;
1721 salt_ptr=salt;
1723 else
1724 { // obtain salt from the first two bytes
1725 String *salt_str=args[1]->val_str(&tmp_value);
1726 if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
1727 return 0;
1728 salt_ptr= salt_str->c_ptr_safe();
1730 pthread_mutex_lock(&LOCK_crypt);
1731 char *tmp= crypt(res->c_ptr_safe(),salt_ptr);
1732 if (!tmp)
1734 pthread_mutex_unlock(&LOCK_crypt);
1735 null_value= 1;
1736 return 0;
1738 str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
1739 str->copy();
1740 pthread_mutex_unlock(&LOCK_crypt);
1741 return str;
1742 #else
1743 null_value=1;
1744 return 0;
1745 #endif /* HAVE_CRYPT */
1748 bool Item_func_encode::seed()
1750 char buf[80];
1751 ulong rand_nr[2];
1752 String *key, tmp(buf, sizeof(buf), system_charset_info);
1754 if (!(key= args[1]->val_str(&tmp)))
1755 return TRUE;
1757 hash_password(rand_nr, key->ptr(), key->length());
1758 sql_crypt.init(rand_nr);
1760 return FALSE;
1763 void Item_func_encode::fix_length_and_dec()
1765 max_length=args[0]->max_length;
1766 maybe_null=args[0]->maybe_null || args[1]->maybe_null;
1767 collation.set(&my_charset_bin);
1768 /* Precompute the seed state if the item is constant. */
1769 seeded= args[1]->const_item() &&
1770 (args[1]->result_type() == STRING_RESULT) && !seed();
1773 String *Item_func_encode::val_str(String *str)
1775 String *res;
1776 DBUG_ASSERT(fixed == 1);
1778 if (!(res=args[0]->val_str(str)))
1780 null_value= 1;
1781 return NULL;
1784 if (!seeded && seed())
1786 null_value= 1;
1787 return NULL;
1790 null_value= 0;
1791 res= copy_if_not_alloced(str, res, res->length());
1792 crypto_transform(res);
1793 sql_crypt.reinit();
1795 return res;
1798 void Item_func_encode::crypto_transform(String *res)
1800 sql_crypt.encode((char*) res->ptr(),res->length());
1801 res->set_charset(&my_charset_bin);
1804 void Item_func_decode::crypto_transform(String *res)
1806 sql_crypt.decode((char*) res->ptr(),res->length());
1810 Item *Item_func_sysconst::safe_charset_converter(CHARSET_INFO *tocs)
1812 Item_string *conv;
1813 uint conv_errors;
1814 String tmp, cstr, *ostr= val_str(&tmp);
1815 if (null_value)
1817 Item *null_item= new Item_null((char *) fully_qualified_func_name());
1818 null_item->collation.set (tocs);
1819 return null_item;
1821 cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
1822 if (conv_errors ||
1823 !(conv= new Item_static_string_func(fully_qualified_func_name(),
1824 cstr.ptr(), cstr.length(),
1825 cstr.charset(),
1826 collation.derivation)))
1828 return NULL;
1830 conv->str_value.copy();
1831 conv->str_value.mark_as_const();
1832 return conv;
1836 String *Item_func_database::val_str(String *str)
1838 DBUG_ASSERT(fixed == 1);
1839 THD *thd= current_thd;
1840 if (thd->db == NULL)
1842 null_value= 1;
1843 return 0;
1845 else
1846 str->copy(thd->db, thd->db_length, system_charset_info);
1847 return str;
1852 @note USER() is replicated correctly if binlog_format=ROW or (as of
1853 BUG#28086) binlog_format=MIXED, but is incorrectly replicated to ''
1854 if binlog_format=STATEMENT.
1856 bool Item_func_user::init(const char *user, const char *host)
1858 DBUG_ASSERT(fixed == 1);
1860 // For system threads (e.g. replication SQL thread) user may be empty
1861 if (user)
1863 CHARSET_INFO *cs= str_value.charset();
1864 size_t res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
1866 if (str_value.alloc((uint) res_length))
1868 null_value=1;
1869 return TRUE;
1872 res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), (uint) res_length,
1873 "%s@%s", user, host);
1874 str_value.length((uint) res_length);
1875 str_value.mark_as_const();
1877 return FALSE;
1881 bool Item_func_user::fix_fields(THD *thd, Item **ref)
1883 return (Item_func_sysconst::fix_fields(thd, ref) ||
1884 init(thd->main_security_ctx.user,
1885 thd->main_security_ctx.host_or_ip));
1889 bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
1891 if (Item_func_sysconst::fix_fields(thd, ref))
1892 return TRUE;
1894 Security_context *ctx=
1895 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1896 (context->security_ctx
1897 ? context->security_ctx : thd->security_ctx);
1898 #else
1899 thd->security_ctx;
1900 #endif /*NO_EMBEDDED_ACCESS_CHECKS*/
1901 return init(ctx->priv_user, ctx->priv_host);
1905 void Item_func_soundex::fix_length_and_dec()
1907 collation.set(args[0]->collation);
1908 max_length=args[0]->max_length;
1909 set_if_bigger(max_length, 4 * collation.collation->mbminlen);
1910 tmp_value.set_charset(collation.collation);
1915 If alpha, map input letter to soundex code.
1916 If not alpha and remove_garbage is set then skip to next char
1917 else return 0
1920 static int soundex_toupper(int ch)
1922 return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch;
1926 static char get_scode(int wc)
1928 int ch= soundex_toupper(wc);
1929 if (ch < 'A' || ch > 'Z')
1931 // Thread extended alfa (country spec)
1932 return '0'; // as vokal
1934 return(soundex_map[ch-'A']);
1938 static bool my_uni_isalpha(int wc)
1941 Return true for all Basic Latin letters: a..z A..Z.
1942 Return true for all Unicode characters with code higher than U+00C0:
1943 - characters between 'z' and U+00C0 are controls and punctuations.
1944 - "U+00C0 LATIN CAPITAL LETTER A WITH GRAVE" is the first letter after 'z'.
1946 return (wc >= 'a' && wc <= 'z') ||
1947 (wc >= 'A' && wc <= 'Z') ||
1948 (wc >= 0xC0);
1952 String *Item_func_soundex::val_str(String *str)
1954 DBUG_ASSERT(fixed == 1);
1955 String *res =args[0]->val_str(str);
1956 char last_ch,ch;
1957 CHARSET_INFO *cs= collation.collation;
1958 my_wc_t wc;
1959 uint nchars;
1960 int rc;
1962 if ((null_value= args[0]->null_value))
1963 return 0; /* purecov: inspected */
1965 if (tmp_value.alloc(max(res->length(), 4 * cs->mbminlen)))
1966 return str; /* purecov: inspected */
1967 char *to= (char *) tmp_value.ptr();
1968 char *to_end= to + tmp_value.alloced_length();
1969 char *from= (char *) res->ptr(), *end= from + res->length();
1971 for ( ; ; ) /* Skip pre-space */
1973 if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
1974 return make_empty_result(); /* EOL or invalid byte sequence */
1976 if (rc == 1 && cs->ctype)
1978 /* Single byte letter found */
1979 if (my_isalpha(cs, *from))
1981 last_ch= get_scode(*from); // Code of the first letter
1982 *to++= soundex_toupper(*from++); // Copy first letter
1983 break;
1985 from++;
1987 else
1989 from+= rc;
1990 if (my_uni_isalpha(wc))
1992 /* Multibyte letter found */
1993 wc= soundex_toupper(wc);
1994 last_ch= get_scode(wc); // Code of the first letter
1995 if ((rc= cs->cset->wc_mb(cs, wc, (uchar*) to, (uchar*) to_end)) <= 0)
1997 /* Extra safety - should not really happen */
1998 DBUG_ASSERT(false);
1999 return make_empty_result();
2001 to+= rc;
2002 break;
2008 last_ch is now set to the first 'double-letter' check.
2009 loop on input letters until end of input
2011 for (nchars= 1 ; ; )
2013 if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2014 break; /* EOL or invalid byte sequence */
2016 if (rc == 1 && cs->ctype)
2018 if (!my_isalpha(cs, *from++))
2019 continue;
2021 else
2023 from+= rc;
2024 if (!my_uni_isalpha(wc))
2025 continue;
2028 ch= get_scode(wc);
2029 if ((ch != '0') && (ch != last_ch)) // if not skipped or double
2031 // letter, copy to output
2032 if ((rc= cs->cset->wc_mb(cs, (my_wc_t) ch,
2033 (uchar*) to, (uchar*) to_end)) <= 0)
2035 // Extra safety - should not really happen
2036 DBUG_ASSERT(false);
2037 break;
2039 to+= rc;
2040 nchars++;
2041 last_ch= ch; // save code of last input letter
2042 } // for next double-letter check
2045 /* Pad up to 4 characters with DIGIT ZERO, if the string is shorter */
2046 if (nchars < 4)
2048 uint nbytes= (4 - nchars) * cs->mbminlen;
2049 cs->cset->fill(cs, to, nbytes, '0');
2050 to+= nbytes;
2053 tmp_value.length((uint) (to-tmp_value.ptr()));
2054 return &tmp_value;
2059 Change a number to format '3,333,333,333.000'.
2061 This should be 'internationalized' sometimes.
2064 const int FORMAT_MAX_DECIMALS= 30;
2066 Item_func_format::Item_func_format(Item *org, Item *dec)
2067 : Item_str_func(org, dec)
2071 void Item_func_format::fix_length_and_dec()
2073 uint char_length= args[0]->max_length/args[0]->collation.collation->mbmaxlen;
2074 uint max_sep_count= char_length/3 + (decimals ? 1 : 0) + /*sign*/1;
2075 collation.set(default_charset());
2076 max_length= (char_length + max_sep_count + decimals) *
2077 collation.collation->mbmaxlen;
2082 @todo
2083 This needs to be fixed for multi-byte character set where numbers
2084 are stored in more than one byte
2087 String *Item_func_format::val_str(String *str)
2089 uint32 length;
2090 uint32 str_length;
2091 /* Number of decimal digits */
2092 int dec;
2093 /* Number of characters used to represent the decimals, including '.' */
2094 uint32 dec_length;
2095 int diff;
2096 DBUG_ASSERT(fixed == 1);
2098 dec= (int) args[1]->val_int();
2099 if (args[1]->null_value)
2101 null_value=1;
2102 return NULL;
2105 dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
2106 dec_length= dec ? dec+1 : 0;
2107 null_value=0;
2109 if (args[0]->result_type() == DECIMAL_RESULT ||
2110 args[0]->result_type() == INT_RESULT)
2112 my_decimal dec_val, rnd_dec, *res;
2113 res= args[0]->val_decimal(&dec_val);
2114 if ((null_value=args[0]->null_value))
2115 return 0; /* purecov: inspected */
2116 my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
2117 my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
2118 str_length= str->length();
2119 if (rnd_dec.sign())
2120 str_length--;
2122 else
2124 double nr= args[0]->val_real();
2125 if ((null_value=args[0]->null_value))
2126 return 0; /* purecov: inspected */
2127 nr= my_double_round(nr, (longlong) dec, FALSE, FALSE);
2128 /* Here default_charset() is right as this is not an automatic conversion */
2129 str->set_real(nr, dec, default_charset());
2130 if (isnan(nr))
2131 return str;
2132 str_length=str->length();
2133 if (nr < 0)
2134 str_length--; // Don't count sign
2136 /* We need this test to handle 'nan' values */
2137 if (str_length >= dec_length+4)
2139 char *tmp,*pos;
2140 length= str->length()+(diff=((int)(str_length- dec_length-1))/3);
2141 str= copy_if_not_alloced(&tmp_str,str,length);
2142 str->length(length);
2143 tmp= (char*) str->ptr()+length - dec_length-1;
2144 for (pos= (char*) str->ptr()+length-1; pos != tmp; pos--)
2145 pos[0]= pos[-diff];
2146 while (diff)
2148 *pos= *(pos - diff);
2149 pos--;
2150 *pos= *(pos - diff);
2151 pos--;
2152 *pos= *(pos - diff);
2153 pos--;
2154 pos[0]=',';
2155 pos--;
2156 diff--;
2159 return str;
2163 void Item_func_format::print(String *str, enum_query_type query_type)
2165 str->append(STRING_WITH_LEN("format("));
2166 args[0]->print(str, query_type);
2167 str->append(',');
2168 args[1]->print(str, query_type);
2169 str->append(')');
2172 void Item_func_elt::fix_length_and_dec()
2174 max_length=0;
2175 decimals=0;
2177 if (agg_arg_charsets(collation, args+1, arg_count-1, MY_COLL_ALLOW_CONV, 1))
2178 return;
2180 for (uint i= 1 ; i < arg_count ; i++)
2182 set_if_bigger(max_length,args[i]->max_length);
2183 set_if_bigger(decimals,args[i]->decimals);
2185 maybe_null=1; // NULL if wrong first arg
2189 double Item_func_elt::val_real()
2191 DBUG_ASSERT(fixed == 1);
2192 uint tmp;
2193 null_value=1;
2194 if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2195 return 0.0;
2196 double result= args[tmp]->val_real();
2197 null_value= args[tmp]->null_value;
2198 return result;
2202 longlong Item_func_elt::val_int()
2204 DBUG_ASSERT(fixed == 1);
2205 uint tmp;
2206 null_value=1;
2207 if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2208 return 0;
2210 longlong result= args[tmp]->val_int();
2211 null_value= args[tmp]->null_value;
2212 return result;
2216 String *Item_func_elt::val_str(String *str)
2218 DBUG_ASSERT(fixed == 1);
2219 uint tmp;
2220 null_value=1;
2221 if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2222 return NULL;
2224 String *result= args[tmp]->val_str(str);
2225 if (result)
2226 result->set_charset(collation.collation);
2227 null_value= args[tmp]->null_value;
2228 return result;
2232 void Item_func_make_set::split_sum_func(THD *thd, Item **ref_pointer_array,
2233 List<Item> &fields)
2235 item->split_sum_func2(thd, ref_pointer_array, fields, &item, TRUE);
2236 Item_str_func::split_sum_func(thd, ref_pointer_array, fields);
2240 void Item_func_make_set::fix_length_and_dec()
2242 max_length=arg_count-1;
2244 if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
2245 return;
2247 for (uint i=0 ; i < arg_count ; i++)
2248 max_length+=args[i]->max_length;
2250 used_tables_cache|= item->used_tables();
2251 not_null_tables_cache&= item->not_null_tables();
2252 const_item_cache&= item->const_item();
2253 with_sum_func= with_sum_func || item->with_sum_func;
2257 void Item_func_make_set::update_used_tables()
2259 Item_func::update_used_tables();
2260 item->update_used_tables();
2261 used_tables_cache|=item->used_tables();
2262 const_item_cache&=item->const_item();
2266 String *Item_func_make_set::val_str(String *str)
2268 DBUG_ASSERT(fixed == 1);
2269 ulonglong bits;
2270 bool first_found=0;
2271 Item **ptr=args;
2272 String *result=&my_empty_string;
2274 bits=item->val_int();
2275 if ((null_value=item->null_value))
2276 return NULL;
2278 if (arg_count < 64)
2279 bits &= ((ulonglong) 1 << arg_count)-1;
2281 for (; bits; bits >>= 1, ptr++)
2283 if (bits & 1)
2285 String *res= (*ptr)->val_str(str);
2286 if (res) // Skip nulls
2288 if (!first_found)
2289 { // First argument
2290 first_found=1;
2291 if (res != str)
2292 result=res; // Use original string
2293 else
2295 if (tmp_str.copy(*res)) // Don't use 'str'
2296 return make_empty_result();
2297 result= &tmp_str;
2300 else
2302 if (result != &tmp_str)
2303 { // Copy data to tmp_str
2304 if (tmp_str.alloc(result->length()+res->length()+1) ||
2305 tmp_str.copy(*result))
2306 return make_empty_result();
2307 result= &tmp_str;
2309 if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
2310 return make_empty_result();
2315 return result;
2319 Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg)
2321 DBUG_ASSERT(!current_thd->is_stmt_prepare());
2323 Item *new_item= item->transform(transformer, arg);
2324 if (!new_item)
2325 return 0;
2328 THD::change_item_tree() should be called only if the tree was
2329 really transformed, i.e. when a new item has been created.
2330 Otherwise we'll be allocating a lot of unnecessary memory for
2331 change records at each execution.
2333 if (item != new_item)
2334 current_thd->change_item_tree(&item, new_item);
2335 return Item_str_func::transform(transformer, arg);
2339 void Item_func_make_set::print(String *str, enum_query_type query_type)
2341 str->append(STRING_WITH_LEN("make_set("));
2342 item->print(str, query_type);
2343 if (arg_count)
2345 str->append(',');
2346 print_args(str, 0, query_type);
2348 str->append(')');
2352 String *Item_func_char::val_str(String *str)
2354 DBUG_ASSERT(fixed == 1);
2355 str->length(0);
2356 str->set_charset(collation.collation);
2357 for (uint i=0 ; i < arg_count ; i++)
2359 int32 num=(int32) args[i]->val_int();
2360 if (!args[i]->null_value)
2362 char char_num= (char) num;
2363 if (num&0xFF000000L) {
2364 str->append((char)(num>>24));
2365 goto b2;
2366 } else if (num&0xFF0000L) {
2367 b2: str->append((char)(num>>16));
2368 goto b1;
2369 } else if (num&0xFF00L) {
2370 b1: str->append((char)(num>>8));
2372 str->append(&char_num, 1);
2375 str->realloc(str->length()); // Add end 0 (for Purify)
2376 return check_well_formed_result(str);
2380 inline String* alloc_buffer(String *res,String *str,String *tmp_value,
2381 ulong length)
2383 if (res->alloced_length() < length)
2385 if (str->alloced_length() >= length)
2387 (void) str->copy(*res);
2388 str->length(length);
2389 return str;
2391 if (tmp_value->alloc(length))
2392 return 0;
2393 (void) tmp_value->copy(*res);
2394 tmp_value->length(length);
2395 return tmp_value;
2397 res->length(length);
2398 return res;
2402 void Item_func_repeat::fix_length_and_dec()
2404 collation.set(args[0]->collation);
2405 if (args[1]->const_item())
2407 /* must be longlong to avoid truncation */
2408 longlong count= args[1]->val_int();
2410 /* Assumes that the maximum length of a String is < INT_MAX32. */
2411 /* Set here so that rest of code sees out-of-bound value as such. */
2412 if (count > INT_MAX32)
2413 count= INT_MAX32;
2415 ulonglong max_result_length= (ulonglong) args[0]->max_length * count;
2416 if (max_result_length >= MAX_BLOB_WIDTH)
2418 max_result_length= MAX_BLOB_WIDTH;
2419 maybe_null= 1;
2421 max_length= (ulong) max_result_length;
2423 else
2425 max_length= MAX_BLOB_WIDTH;
2426 maybe_null= 1;
2431 Item_func_repeat::str is carefully written to avoid reallocs
2432 as much as possible at the cost of a local buffer
2435 String *Item_func_repeat::val_str(String *str)
2437 DBUG_ASSERT(fixed == 1);
2438 uint length,tot_length;
2439 char *to;
2440 /* must be longlong to avoid truncation */
2441 longlong count= args[1]->val_int();
2442 String *res= args[0]->val_str(str);
2444 if (args[0]->null_value || args[1]->null_value)
2445 goto err; // string and/or delim are null
2446 null_value= 0;
2448 if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
2449 return make_empty_result();
2451 /* Assumes that the maximum length of a String is < INT_MAX32. */
2452 /* Bounds check on count: If this is triggered, we will error. */
2453 if ((ulonglong) count > INT_MAX32)
2454 count= INT_MAX32;
2455 if (count == 1) // To avoid reallocs
2456 return res;
2457 length=res->length();
2458 // Safe length check
2459 if (length > current_thd->variables.max_allowed_packet / (uint) count)
2461 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2462 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2463 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2464 func_name(), current_thd->variables.max_allowed_packet);
2465 goto err;
2467 tot_length= length*(uint) count;
2468 if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
2469 goto err;
2471 to=(char*) res->ptr()+length;
2472 while (--count)
2474 memcpy(to,res->ptr(),length);
2475 to+=length;
2477 return (res);
2479 err:
2480 null_value=1;
2481 return 0;
2485 void Item_func_rpad::fix_length_and_dec()
2487 // Handle character set for args[0] and args[2].
2488 if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
2489 return;
2490 if (args[1]->const_item())
2492 ulonglong length= 0;
2494 if (collation.collation->mbmaxlen > 0)
2496 ulonglong temp= (ulonglong) args[1]->val_int();
2498 /* Assumes that the maximum length of a String is < INT_MAX32. */
2499 /* Set here so that rest of code sees out-of-bound value as such. */
2500 if (temp > INT_MAX32)
2501 temp = INT_MAX32;
2503 length= temp * collation.collation->mbmaxlen;
2506 if (length >= MAX_BLOB_WIDTH)
2508 length= MAX_BLOB_WIDTH;
2509 maybe_null= 1;
2511 max_length= (ulong) length;
2513 else
2515 max_length= MAX_BLOB_WIDTH;
2516 maybe_null= 1;
2521 String *Item_func_rpad::val_str(String *str)
2523 DBUG_ASSERT(fixed == 1);
2524 uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
2525 char *to;
2526 const char *ptr_pad;
2527 /* must be longlong to avoid truncation */
2528 longlong count= args[1]->val_int();
2529 longlong byte_count;
2530 String *res= args[0]->val_str(str);
2531 String *rpad= args[2]->val_str(&rpad_str);
2533 if (!res || args[1]->null_value || !rpad ||
2534 ((count < 0) && !args[1]->unsigned_flag))
2535 goto err;
2536 null_value=0;
2537 /* Assumes that the maximum length of a String is < INT_MAX32. */
2538 /* Set here so that rest of code sees out-of-bound value as such. */
2539 if ((ulonglong) count > INT_MAX32)
2540 count= INT_MAX32;
2542 There is one exception not handled (intentionaly) by the character set
2543 aggregation code. If one string is strong side and is binary, and
2544 another one is weak side and is a multi-byte character string,
2545 then we need to operate on the second string in terms on bytes when
2546 calling ::numchars() and ::charpos(), rather than in terms of characters.
2547 Lets substitute its character set to binary.
2549 if (collation.collation == &my_charset_bin)
2551 res->set_charset(&my_charset_bin);
2552 rpad->set_charset(&my_charset_bin);
2555 if (count <= (res_char_length= res->numchars()))
2556 { // String to pad is big enough
2557 res->length(res->charpos((int) count)); // Shorten result if longer
2558 return (res);
2560 pad_char_length= rpad->numchars();
2562 byte_count= count * collation.collation->mbmaxlen;
2563 if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2565 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2566 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2567 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2568 func_name(), current_thd->variables.max_allowed_packet);
2569 goto err;
2571 if (args[2]->null_value || !pad_char_length)
2572 goto err;
2573 res_byte_length= res->length(); /* Must be done before alloc_buffer */
2574 if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
2575 goto err;
2577 to= (char*) res->ptr()+res_byte_length;
2578 ptr_pad=rpad->ptr();
2579 pad_byte_length= rpad->length();
2580 count-= res_char_length;
2581 for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
2583 memcpy(to,ptr_pad,pad_byte_length);
2584 to+= pad_byte_length;
2586 if (count)
2588 pad_byte_length= rpad->charpos((int) count);
2589 memcpy(to,ptr_pad,(size_t) pad_byte_length);
2590 to+= pad_byte_length;
2592 res->length((uint) (to- (char*) res->ptr()));
2593 return (res);
2595 err:
2596 null_value=1;
2597 return 0;
2601 void Item_func_lpad::fix_length_and_dec()
2603 // Handle character set for args[0] and args[2].
2604 if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
2605 return;
2607 if (args[1]->const_item())
2609 ulonglong length= 0;
2611 if (collation.collation->mbmaxlen > 0)
2613 ulonglong temp= (ulonglong) args[1]->val_int();
2615 /* Assumes that the maximum length of a String is < INT_MAX32. */
2616 /* Set here so that rest of code sees out-of-bound value as such. */
2617 if (temp > INT_MAX32)
2618 temp= INT_MAX32;
2620 length= temp * collation.collation->mbmaxlen;
2623 if (length >= MAX_BLOB_WIDTH)
2625 length= MAX_BLOB_WIDTH;
2626 maybe_null= 1;
2628 max_length= (ulong) length;
2630 else
2632 max_length= MAX_BLOB_WIDTH;
2633 maybe_null= 1;
2638 String *Item_func_lpad::val_str(String *str)
2640 DBUG_ASSERT(fixed == 1);
2641 uint32 res_char_length,pad_char_length;
2642 /* must be longlong to avoid truncation */
2643 longlong count= args[1]->val_int();
2644 longlong byte_count;
2645 String *res= args[0]->val_str(&tmp_value);
2646 String *pad= args[2]->val_str(&lpad_str);
2648 if (!res || args[1]->null_value || !pad ||
2649 ((count < 0) && !args[1]->unsigned_flag))
2650 goto err;
2651 null_value=0;
2652 /* Assumes that the maximum length of a String is < INT_MAX32. */
2653 /* Set here so that rest of code sees out-of-bound value as such. */
2654 if ((ulonglong) count > INT_MAX32)
2655 count= INT_MAX32;
2658 There is one exception not handled (intentionaly) by the character set
2659 aggregation code. If one string is strong side and is binary, and
2660 another one is weak side and is a multi-byte character string,
2661 then we need to operate on the second string in terms on bytes when
2662 calling ::numchars() and ::charpos(), rather than in terms of characters.
2663 Lets substitute its character set to binary.
2665 if (collation.collation == &my_charset_bin)
2667 res->set_charset(&my_charset_bin);
2668 pad->set_charset(&my_charset_bin);
2671 res_char_length= res->numchars();
2673 if (count <= res_char_length)
2675 res->length(res->charpos((int) count));
2676 return res;
2679 pad_char_length= pad->numchars();
2680 byte_count= count * collation.collation->mbmaxlen;
2682 if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2684 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2685 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2686 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2687 func_name(), current_thd->variables.max_allowed_packet);
2688 goto err;
2691 if (args[2]->null_value || !pad_char_length ||
2692 str->alloc((uint32) byte_count))
2693 goto err;
2695 str->length(0);
2696 str->set_charset(collation.collation);
2697 count-= res_char_length;
2698 while (count >= pad_char_length)
2700 str->append(*pad);
2701 count-= pad_char_length;
2703 if (count > 0)
2704 str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
2706 str->append(*res);
2707 null_value= 0;
2708 return str;
2710 err:
2711 null_value= 1;
2712 return 0;
2716 String *Item_func_conv::val_str(String *str)
2718 DBUG_ASSERT(fixed == 1);
2719 String *res= args[0]->val_str(str);
2720 char *endptr,ans[65],*ptr;
2721 longlong dec;
2722 int from_base= (int) args[1]->val_int();
2723 int to_base= (int) args[2]->val_int();
2724 int err;
2726 if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
2727 abs(to_base) > 36 || abs(to_base) < 2 ||
2728 abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
2730 null_value= 1;
2731 return NULL;
2733 null_value= 0;
2734 unsigned_flag= !(from_base < 0);
2736 if (args[0]->field_type() == MYSQL_TYPE_BIT)
2739 Special case: The string representation of BIT doesn't resemble the
2740 decimal representation, so we shouldn't change it to string and then to
2741 decimal.
2743 dec= args[0]->val_int();
2745 else
2747 if (from_base < 0)
2748 dec= my_strntoll(res->charset(), res->ptr(), res->length(),
2749 -from_base, &endptr, &err);
2750 else
2751 dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
2752 from_base, &endptr, &err);
2755 ptr= longlong2str(dec, ans, to_base);
2756 if (str->copy(ans, (uint32) (ptr-ans), default_charset()))
2757 return make_empty_result();
2758 return str;
2762 String *Item_func_conv_charset::val_str(String *str)
2764 DBUG_ASSERT(fixed == 1);
2765 if (use_cached_value)
2766 return null_value ? 0 : &str_value;
2767 String *arg= args[0]->val_str(str);
2768 uint dummy_errors;
2769 if (!arg)
2771 null_value=1;
2772 return 0;
2774 null_value= tmp_value.copy(arg->ptr(), arg->length(), arg->charset(),
2775 conv_charset, &dummy_errors);
2776 return null_value ? 0 : check_well_formed_result(&tmp_value);
2779 void Item_func_conv_charset::fix_length_and_dec()
2781 collation.set(conv_charset, DERIVATION_IMPLICIT);
2782 max_length = args[0]->max_length*conv_charset->mbmaxlen;
2785 void Item_func_conv_charset::print(String *str, enum_query_type query_type)
2787 str->append(STRING_WITH_LEN("convert("));
2788 args[0]->print(str, query_type);
2789 str->append(STRING_WITH_LEN(" using "));
2790 str->append(conv_charset->csname);
2791 str->append(')');
2794 String *Item_func_set_collation::val_str(String *str)
2796 DBUG_ASSERT(fixed == 1);
2797 str=args[0]->val_str(str);
2798 if ((null_value=args[0]->null_value))
2799 return 0;
2800 str->set_charset(collation.collation);
2801 return str;
2804 void Item_func_set_collation::fix_length_and_dec()
2806 CHARSET_INFO *set_collation;
2807 const char *colname;
2808 String tmp, *str= args[1]->val_str(&tmp);
2809 colname= str->c_ptr();
2810 if (colname == binary_keyword)
2811 set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
2812 MY_CS_BINSORT,MYF(0));
2813 else
2815 if (!(set_collation= get_charset_by_name(colname,MYF(0))))
2817 my_error(ER_UNKNOWN_COLLATION, MYF(0), colname);
2818 return;
2822 if (!set_collation ||
2823 !my_charset_same(args[0]->collation.collation,set_collation))
2825 my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
2826 colname, args[0]->collation.collation->csname);
2827 return;
2829 collation.set(set_collation, DERIVATION_EXPLICIT,
2830 args[0]->collation.repertoire);
2831 max_length= args[0]->max_length;
2835 bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
2837 /* Assume we don't have rtti */
2838 if (this == item)
2839 return 1;
2840 if (item->type() != FUNC_ITEM)
2841 return 0;
2842 Item_func *item_func=(Item_func*) item;
2843 if (arg_count != item_func->arg_count ||
2844 functype() != item_func->functype())
2845 return 0;
2846 Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
2847 if (collation.collation != item_func_sc->collation.collation)
2848 return 0;
2849 for (uint i=0; i < arg_count ; i++)
2850 if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
2851 return 0;
2852 return 1;
2856 void Item_func_set_collation::print(String *str, enum_query_type query_type)
2858 str->append('(');
2859 args[0]->print(str, query_type);
2860 str->append(STRING_WITH_LEN(" collate "));
2861 DBUG_ASSERT(args[1]->basic_const_item() &&
2862 args[1]->type() == Item::STRING_ITEM);
2863 args[1]->str_value.print(str);
2864 str->append(')');
2867 String *Item_func_charset::val_str(String *str)
2869 DBUG_ASSERT(fixed == 1);
2870 uint dummy_errors;
2872 CHARSET_INFO *cs= args[0]->collation.collation;
2873 null_value= 0;
2874 str->copy(cs->csname, (uint) strlen(cs->csname),
2875 &my_charset_latin1, collation.collation, &dummy_errors);
2876 return str;
2879 String *Item_func_collation::val_str(String *str)
2881 DBUG_ASSERT(fixed == 1);
2882 uint dummy_errors;
2883 CHARSET_INFO *cs= args[0]->collation.collation;
2885 null_value= 0;
2886 str->copy(cs->name, (uint) strlen(cs->name),
2887 &my_charset_latin1, collation.collation, &dummy_errors);
2888 return str;
2892 String *Item_func_hex::val_str(String *str)
2894 String *res;
2895 DBUG_ASSERT(fixed == 1);
2896 if (args[0]->result_type() != STRING_RESULT)
2898 ulonglong dec;
2899 char ans[65],*ptr;
2900 /* Return hex of unsigned longlong value */
2901 if (args[0]->result_type() == REAL_RESULT ||
2902 args[0]->result_type() == DECIMAL_RESULT)
2904 double val= args[0]->val_real();
2905 if ((val <= (double) LONGLONG_MIN) ||
2906 (val >= (double) (ulonglong) ULONGLONG_MAX))
2907 dec= ~(longlong) 0;
2908 else
2909 dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
2911 else
2912 dec= (ulonglong) args[0]->val_int();
2914 if ((null_value= args[0]->null_value))
2915 return 0;
2916 ptr= longlong2str(dec,ans,16);
2917 if (str->copy(ans,(uint32) (ptr-ans),default_charset()))
2918 return make_empty_result(); // End of memory
2919 return str;
2922 /* Convert given string to a hex string, character by character */
2923 res= args[0]->val_str(str);
2924 if (!res || tmp_value.alloc(res->length()*2+1))
2926 null_value=1;
2927 return 0;
2929 null_value=0;
2930 tmp_value.length(res->length()*2);
2932 octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
2933 return &tmp_value;
2936 /** Convert given hex string to a binary string. */
2938 String *Item_func_unhex::val_str(String *str)
2940 const char *from, *end;
2941 char *to;
2942 String *res;
2943 uint length;
2944 DBUG_ASSERT(fixed == 1);
2946 res= args[0]->val_str(str);
2947 if (!res || tmp_value.alloc(length= (1+res->length())/2))
2949 null_value=1;
2950 return 0;
2953 from= res->ptr();
2954 null_value= 0;
2955 tmp_value.length(length);
2956 to= (char*) tmp_value.ptr();
2957 if (res->length() % 2)
2959 int hex_char;
2960 *to++= hex_char= hexchar_to_int(*from++);
2961 if ((null_value= (hex_char == -1)))
2962 return 0;
2964 for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
2966 int hex_char;
2967 *to= (hex_char= hexchar_to_int(from[0])) << 4;
2968 if ((null_value= (hex_char == -1)))
2969 return 0;
2970 *to|= hex_char= hexchar_to_int(from[1]);
2971 if ((null_value= (hex_char == -1)))
2972 return 0;
2974 return &tmp_value;
2978 void Item_func_binary::print(String *str, enum_query_type query_type)
2980 str->append(STRING_WITH_LEN("cast("));
2981 args[0]->print(str, query_type);
2982 str->append(STRING_WITH_LEN(" as binary)"));
2986 #include <my_dir.h> // For my_stat
2988 String *Item_load_file::val_str(String *str)
2990 DBUG_ASSERT(fixed == 1);
2991 String *file_name;
2992 File file;
2993 MY_STAT stat_info;
2994 char path[FN_REFLEN];
2995 DBUG_ENTER("load_file");
2997 if (!(file_name= args[0]->val_str(str))
2998 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2999 || !(current_thd->security_ctx->master_access & FILE_ACL)
3000 #endif
3002 goto err;
3004 (void) fn_format(path, file_name->c_ptr_safe(), mysql_real_data_home, "",
3005 MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
3007 /* Read only allowed from within dir specified by secure_file_priv */
3008 if (!is_secure_file_path(path))
3009 goto err;
3011 if (!my_stat(path, &stat_info, MYF(0)))
3012 goto err;
3014 if (!(stat_info.st_mode & S_IROTH))
3016 /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
3017 goto err;
3019 if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
3021 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
3022 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3023 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3024 func_name(), current_thd->variables.max_allowed_packet);
3025 goto err;
3027 if (tmp_value.alloc(stat_info.st_size))
3028 goto err;
3029 if ((file = my_open(file_name->ptr(), O_RDONLY, MYF(0))) < 0)
3030 goto err;
3031 if (my_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size, MYF(MY_NABP)))
3033 my_close(file, MYF(0));
3034 goto err;
3036 tmp_value.length(stat_info.st_size);
3037 my_close(file, MYF(0));
3038 null_value = 0;
3039 DBUG_RETURN(&tmp_value);
3041 err:
3042 null_value = 1;
3043 DBUG_RETURN(0);
3047 String* Item_func_export_set::val_str(String* str)
3049 DBUG_ASSERT(fixed == 1);
3050 String yes_buf, no_buf, sep_buf;
3051 const ulonglong the_set = (ulonglong) args[0]->val_int();
3052 const String *yes= args[1]->val_str(&yes_buf);
3053 const String *no= args[2]->val_str(&no_buf);
3054 const String *sep= NULL;
3056 uint num_set_values = 64;
3057 str->length(0);
3058 str->set_charset(collation.collation);
3060 /* Check if some argument is a NULL value */
3061 if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
3063 null_value= true;
3064 return NULL;
3067 Arg count can only be 3, 4 or 5 here. This is guaranteed from the
3068 grammar for EXPORT_SET()
3070 switch(arg_count) {
3071 case 5:
3072 num_set_values = (uint) args[4]->val_int();
3073 if (num_set_values > 64)
3074 num_set_values=64;
3075 if (args[4]->null_value)
3077 null_value= true;
3078 return NULL;
3080 /* Fall through */
3081 case 4:
3082 if (!(sep = args[3]->val_str(&sep_buf))) // Only true if NULL
3084 null_value= true;
3085 return NULL;
3087 break;
3088 case 3:
3090 /* errors is not checked - assume "," can always be converted */
3091 uint errors;
3092 sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin,
3093 collation.collation, &errors);
3094 sep = &sep_buf;
3096 break;
3097 default:
3098 DBUG_ASSERT(0); // cannot happen
3100 null_value= false;
3102 const ulong max_allowed_packet= current_thd->variables.max_allowed_packet;
3103 const uint num_separators= num_set_values > 0 ? num_set_values - 1 : 0;
3104 const ulonglong max_total_length=
3105 num_set_values * max(yes->length(), no->length()) +
3106 num_separators * sep->length();
3108 if (unlikely(max_total_length > max_allowed_packet))
3110 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
3111 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3112 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3113 func_name(), max_allowed_packet);
3114 null_value= true;
3115 return NULL;
3118 uint ix;
3119 ulonglong mask;
3120 for (ix= 0, mask=0x1; ix < num_set_values; ++ix, mask = (mask << 1))
3122 if (the_set & mask)
3123 str->append(*yes);
3124 else
3125 str->append(*no);
3126 if (ix != num_separators)
3127 str->append(*sep);
3129 return str;
3132 void Item_func_export_set::fix_length_and_dec()
3134 uint length=max(args[1]->max_length,args[2]->max_length);
3135 uint sep_length=(arg_count > 3 ? args[3]->max_length : 1);
3136 max_length=length*64+sep_length*63;
3138 if (agg_arg_charsets(collation, args+1, min(4,arg_count)-1,
3139 MY_COLL_ALLOW_CONV, 1))
3140 return;
3143 String* Item_func_inet_ntoa::val_str(String* str)
3145 DBUG_ASSERT(fixed == 1);
3146 uchar buf[8], *p;
3147 ulonglong n = (ulonglong) args[0]->val_int();
3148 char num[4];
3151 We do not know if args[0] is NULL until we have called
3152 some val function on it if args[0] is not a constant!
3154 Also return null if n > 255.255.255.255
3156 if ((null_value= (args[0]->null_value || n > (ulonglong) LL(4294967295))))
3157 return 0; // Null value
3159 str->set_charset(collation.collation);
3160 str->length(0);
3161 int4store(buf,n);
3163 /* Now we can assume little endian. */
3165 num[3]='.';
3166 for (p=buf+4 ; p-- > buf ; )
3168 uint c = *p;
3169 uint n1,n2; // Try to avoid divisions
3170 n1= c / 100; // 100 digits
3171 c-= n1*100;
3172 n2= c / 10; // 10 digits
3173 c-=n2*10; // last digit
3174 num[0]=(char) n1+'0';
3175 num[1]=(char) n2+'0';
3176 num[2]=(char) c+'0';
3177 uint length=(n1 ? 4 : n2 ? 3 : 2); // Remove pre-zero
3179 (void) str->append(num+4-length,length);
3181 str->length(str->length()-1); // Remove last '.';
3182 return str;
3186 #define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))
3189 QUOTE() function returns argument string in single quotes suitable for
3190 using in a SQL statement.
3192 Adds a \\ before all characters that needs to be escaped in a SQL string.
3193 We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
3194 running commands from a file in windows.
3196 This function is very useful when you want to generate SQL statements.
3198 @note
3199 QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).
3201 @retval
3202 str Quoted string
3203 @retval
3204 NULL Out of memory.
3207 String *Item_func_quote::val_str(String *str)
3209 DBUG_ASSERT(fixed == 1);
3211 Bit mask that has 1 for set for the position of the following characters:
3212 0, \, ' and ^Z
3215 static uchar escmask[32]=
3217 0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
3218 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
3219 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3220 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
3223 char *from, *to, *end, *start;
3224 String *arg= args[0]->val_str(str);
3225 uint arg_length, new_length;
3226 if (!arg) // Null argument
3228 /* Return the string 'NULL' */
3229 str->copy(STRING_WITH_LEN("NULL"), collation.collation);
3230 null_value= 0;
3231 return str;
3234 arg_length= arg->length();
3236 if (collation.collation->mbmaxlen == 1)
3238 new_length= arg_length + 2; /* for beginning and ending ' signs */
3239 for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
3240 new_length+= get_esc_bit(escmask, (uchar) *from);
3242 else
3244 new_length= (arg_length * 2) + /* For string characters */
3245 (2 * collation.collation->mbmaxlen); /* For quotes */
3248 if (tmp_value.alloc(new_length))
3249 goto null;
3251 if (collation.collation->mbmaxlen > 1)
3253 CHARSET_INFO *cs= collation.collation;
3254 int mblen;
3255 uchar *to_end;
3256 to= (char*) tmp_value.ptr();
3257 to_end= (uchar*) to + new_length;
3259 /* Put leading quote */
3260 if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
3261 goto null;
3262 to+= mblen;
3264 for (start= (char*) arg->ptr(), end= start + arg_length; start < end; )
3266 my_wc_t wc;
3267 bool escape;
3268 if ((mblen= cs->cset->mb_wc(cs, &wc, (uchar*) start, (uchar*) end)) <= 0)
3269 goto null;
3270 start+= mblen;
3271 switch (wc) {
3272 case 0: escape= 1; wc= '0'; break;
3273 case '\032': escape= 1; wc= 'Z'; break;
3274 case '\'': escape= 1; break;
3275 case '\\': escape= 1; break;
3276 default: escape= 0; break;
3278 if (escape)
3280 if ((mblen= cs->cset->wc_mb(cs, '\\', (uchar*) to, to_end)) <= 0)
3281 goto null;
3282 to+= mblen;
3284 if ((mblen= cs->cset->wc_mb(cs, wc, (uchar*) to, to_end)) <= 0)
3285 goto null;
3286 to+= mblen;
3289 /* Put trailing quote */
3290 if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
3291 goto null;
3292 to+= mblen;
3293 new_length= to - tmp_value.ptr();
3294 goto ret;
3298 We replace characters from the end to the beginning
3300 to= (char*) tmp_value.ptr() + new_length - 1;
3301 *to--= '\'';
3302 for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
3305 We can't use the bitmask here as we want to replace \O and ^Z with 0
3306 and Z
3308 switch (*end) {
3309 case 0:
3310 *to--= '0';
3311 *to= '\\';
3312 break;
3313 case '\032':
3314 *to--= 'Z';
3315 *to= '\\';
3316 break;
3317 case '\'':
3318 case '\\':
3319 *to--= *end;
3320 *to= '\\';
3321 break;
3322 default:
3323 *to= *end;
3324 break;
3327 *to= '\'';
3329 ret:
3330 tmp_value.length(new_length);
3331 tmp_value.set_charset(collation.collation);
3332 null_value= 0;
3333 return &tmp_value;
3335 null:
3336 null_value= 1;
3337 return 0;
3340 longlong Item_func_uncompressed_length::val_int()
3342 DBUG_ASSERT(fixed == 1);
3343 String *res= args[0]->val_str(&value);
3344 if (!res)
3346 null_value=1;
3347 return 0; /* purecov: inspected */
3349 null_value=0;
3350 if (res->is_empty()) return 0;
3353 If length is <= 4 bytes, data is corrupt. This is the best we can do
3354 to detect garbage input without decompressing it.
3356 if (res->length() <= 4)
3358 push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
3359 ER_ZLIB_Z_DATA_ERROR,
3360 ER(ER_ZLIB_Z_DATA_ERROR));
3361 null_value= 1;
3362 return 0;
3366 res->ptr() using is safe because we have tested that string is at least
3367 5 bytes long.
3368 res->c_ptr() is not used because:
3369 - we do not need \0 terminated string to get first 4 bytes
3370 - c_ptr() tests simbol after string end (uninitialiozed memory) which
3371 confuse valgrind
3373 return uint4korr(res->ptr()) & 0x3FFFFFFF;
3376 longlong Item_func_crc32::val_int()
3378 DBUG_ASSERT(fixed == 1);
3379 String *res=args[0]->val_str(&value);
3380 if (!res)
3382 null_value=1;
3383 return 0; /* purecov: inspected */
3385 null_value=0;
3386 return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
3389 #ifdef HAVE_COMPRESS
3390 #include "zlib.h"
3392 String *Item_func_compress::val_str(String *str)
3394 int err= Z_OK, code;
3395 ulong new_size;
3396 String *res;
3397 Byte *body;
3398 char *tmp, *last_char;
3399 DBUG_ASSERT(fixed == 1);
3401 if (!(res= args[0]->val_str(str)))
3403 null_value= 1;
3404 return 0;
3406 null_value= 0;
3407 if (res->is_empty()) return res;
3410 Citation from zlib.h (comment for compress function):
3412 Compresses the source buffer into the destination buffer. sourceLen is
3413 the byte length of the source buffer. Upon entry, destLen is the total
3414 size of the destination buffer, which must be at least 0.1% larger than
3415 sourceLen plus 12 bytes.
3416 We assume here that the buffer can't grow more than .25 %.
3418 new_size= res->length() + res->length() / 5 + 12;
3420 // Check new_size overflow: new_size <= res->length()
3421 if (((uint32) (new_size+5) <= res->length()) ||
3422 buffer.realloc((uint32) new_size + 4 + 1))
3424 null_value= 1;
3425 return 0;
3428 body= ((Byte*)buffer.ptr()) + 4;
3430 // As far as we have checked res->is_empty() we can use ptr()
3431 if ((err= compress(body, &new_size,
3432 (const Bytef*)res->ptr(), res->length())) != Z_OK)
3434 code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
3435 push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
3436 null_value= 1;
3437 return 0;
3440 tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
3441 int4store(tmp, res->length() & 0x3FFFFFFF);
3443 /* This is to ensure that things works for CHAR fields, which trim ' ': */
3444 last_char= ((char*)body)+new_size-1;
3445 if (*last_char == ' ')
3447 *++last_char= '.';
3448 new_size++;
3451 buffer.length((uint32)new_size + 4);
3452 return &buffer;
3456 String *Item_func_uncompress::val_str(String *str)
3458 DBUG_ASSERT(fixed == 1);
3459 String *res= args[0]->val_str(str);
3460 ulong new_size;
3461 int err;
3462 uint code;
3464 if (!res)
3465 goto err;
3466 null_value= 0;
3467 if (res->is_empty())
3468 return res;
3470 /* If length is less than 4 bytes, data is corrupt */
3471 if (res->length() <= 4)
3473 push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
3474 ER_ZLIB_Z_DATA_ERROR,
3475 ER(ER_ZLIB_Z_DATA_ERROR));
3476 goto err;
3479 /* Size of uncompressed data is stored as first 4 bytes of field */
3480 new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
3481 if (new_size > current_thd->variables.max_allowed_packet)
3483 push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
3484 ER_TOO_BIG_FOR_UNCOMPRESS,
3485 ER(ER_TOO_BIG_FOR_UNCOMPRESS),
3486 static_cast<int>(current_thd->variables.
3487 max_allowed_packet));
3488 goto err;
3490 if (buffer.realloc((uint32)new_size))
3491 goto err;
3493 if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
3494 ((const Bytef*)res->ptr())+4,res->length())) == Z_OK)
3496 buffer.length((uint32) new_size);
3497 return &buffer;
3500 code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
3501 ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
3502 push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
3504 err:
3505 null_value= 1;
3506 return 0;
3508 #endif
3511 UUID, as in
3512 DCE 1.1: Remote Procedure Call,
3513 Open Group Technical Standard Document Number C706, October 1997,
3514 (supersedes C309 DCE: Remote Procedure Call 8/1994,
3515 which was basis for ISO/IEC 11578:1996 specification)
3518 static struct rand_struct uuid_rand;
3519 static uint nanoseq;
3520 static ulonglong uuid_time=0;
3521 static char clock_seq_and_node_str[]="-0000-000000000000";
3524 number of 100-nanosecond intervals between
3525 1582-10-15 00:00:00.00 and 1970-01-01 00:00:00.00.
3527 #define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * \
3528 1000 * 1000 * 10)
3530 #define UUID_VERSION 0x1000
3531 #define UUID_VARIANT 0x8000
3533 static void tohex(char *to, uint from, uint len)
3535 to+= len;
3536 while (len--)
3538 *--to= _dig_vec_lower[from & 15];
3539 from >>= 4;
3543 static void set_clock_seq_str()
3545 uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT;
3546 tohex(clock_seq_and_node_str+1, clock_seq, 4);
3547 nanoseq= 0;
3550 String *Item_func_uuid::val_str(String *str)
3552 DBUG_ASSERT(fixed == 1);
3553 char *s;
3554 THD *thd= current_thd;
3556 pthread_mutex_lock(&LOCK_uuid_generator);
3557 if (! uuid_time) /* first UUID() call. initializing data */
3559 ulong tmp=sql_rnd_with_mutex();
3560 uchar mac[6];
3561 int i;
3562 if (my_gethwaddr(mac))
3564 /* purecov: begin inspected */
3566 generating random "hardware addr"
3567 and because specs explicitly specify that it should NOT correlate
3568 with a clock_seq value (initialized random below), we use a separate
3569 randominit() here
3571 randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)global_query_id);
3572 for (i=0; i < (int)sizeof(mac); i++)
3573 mac[i]=(uchar)(my_rnd(&uuid_rand)*255);
3574 /* purecov: end */
3576 s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1;
3577 for (i=sizeof(mac)-1 ; i>=0 ; i--)
3579 *--s=_dig_vec_lower[mac[i] & 15];
3580 *--s=_dig_vec_lower[mac[i] >> 4];
3582 randominit(&uuid_rand, tmp + (ulong) server_start_time,
3583 tmp + (ulong) thd->status_var.bytes_sent);
3584 set_clock_seq_str();
3587 ulonglong tv= my_getsystime() + UUID_TIME_OFFSET + nanoseq;
3589 if (likely(tv > uuid_time))
3592 Current time is ahead of last timestamp, as it should be.
3593 If we "borrowed time", give it back, just as long as we
3594 stay ahead of the previous timestamp.
3596 if (nanoseq)
3598 DBUG_ASSERT((tv > uuid_time) && (nanoseq > 0));
3600 -1 so we won't make tv= uuid_time for nanoseq >= (tv - uuid_time)
3602 ulong delta= min(nanoseq, (ulong) (tv - uuid_time -1));
3603 tv-= delta;
3604 nanoseq-= delta;
3607 else
3609 if (unlikely(tv == uuid_time))
3612 For low-res system clocks. If several requests for UUIDs
3613 end up on the same tick, we add a nano-second to make them
3614 different.
3615 ( current_timestamp + nanoseq * calls_in_this_period )
3616 may end up > next_timestamp; this is OK. Nonetheless, we'll
3617 try to unwind nanoseq when we get a chance to.
3618 If nanoseq overflows, we'll start over with a new numberspace
3619 (so the if() below is needed so we can avoid the ++tv and thus
3620 match the follow-up if() if nanoseq overflows!).
3622 if (likely(++nanoseq))
3623 ++tv;
3626 if (unlikely(tv <= uuid_time))
3629 If the admin changes the system clock (or due to Daylight
3630 Saving Time), the system clock may be turned *back* so we
3631 go through a period once more for which we already gave out
3632 UUIDs. To avoid duplicate UUIDs despite potentially identical
3633 times, we make a new random component.
3634 We also come here if the nanoseq "borrowing" overflows.
3635 In either case, we throw away any nanoseq borrowing since it's
3636 irrelevant in the new numberspace.
3638 set_clock_seq_str();
3639 tv= my_getsystime() + UUID_TIME_OFFSET;
3640 nanoseq= 0;
3641 DBUG_PRINT("uuid",("making new numberspace"));
3645 uuid_time=tv;
3646 pthread_mutex_unlock(&LOCK_uuid_generator);
3648 uint32 time_low= (uint32) (tv & 0xFFFFFFFF);
3649 uint16 time_mid= (uint16) ((tv >> 32) & 0xFFFF);
3650 uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION);
3652 str->realloc(UUID_LENGTH+1);
3653 str->length(UUID_LENGTH);
3654 str->set_charset(system_charset_info);
3655 s=(char *) str->ptr();
3656 s[8]=s[13]='-';
3657 tohex(s, time_low, 8);
3658 tohex(s+9, time_mid, 4);
3659 tohex(s+14, time_hi_and_version, 4);
3660 strmov(s+18, clock_seq_and_node_str);
3661 return str;