1/*
2 Copyright (c) 2000, 2017, Oracle and/or its affiliates.
3 Copyright (c) 2009, 2018, MariaDB Corporation
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; version 2 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17*/
18
19/**
20 @file
21
22 @brief
23 This file defines all string functions
24
25 @warning
26 Some string functions don't always put and end-null on a String.
27 (This shouldn't be needed)
28*/
29
30#ifdef USE_PRAGMA_IMPLEMENTATION
31#pragma implementation // gcc: Class implementation
32#endif
33
34#include "mariadb.h" // HAVE_*
35
36#include "sql_priv.h"
37/*
38 It is necessary to include set_var.h instead of item.h because there
39 are dependencies on include order for set_var.h and item.h. This
40 will be resolved later.
41*/
42#include "sql_class.h" // set_var.h: THD
43#include "set_var.h"
44#include "sql_base.h"
45#include "sql_time.h"
46#include "sql_acl.h" // SUPER_ACL
47#include "des_key_file.h" // st_des_keyschedule, st_des_keyblock
48#include "password.h" // my_make_scrambled_password,
49 // my_make_scrambled_password_323
50#include <m_ctype.h>
51#include <my_md5.h>
52C_MODE_START
53#include "../mysys/my_static.h" // For soundex_map
54C_MODE_END
55#include "sql_show.h" // append_identifier
56#include <sql_repl.h>
57#include "sql_statistics.h"
58
59size_t username_char_length= 80;
60
61/*
62 For the Items which have only val_str_ascii() method
63 and don't have their own "native" val_str(),
64 we provide a "wrapper" method to convert from ASCII
65 to Item character set when it's necessary.
66 Conversion happens only in case of "tricky" Item character set (e.g. UCS2).
67 Normally conversion does not happen, and val_str_ascii() is immediately
68 returned instead.
69
70 No matter if conversion is needed or not needed,
71 the result is always returned in "str" (see MDEV-10306 why).
72
73 @param [OUT] str - Store the result here
74 @param [IN] ascii_buffer - Use this temporary buffer to call val_str_ascii()
75*/
76String *Item_func::val_str_from_val_str_ascii(String *str, String *ascii_buffer)
77{
78 DBUG_ASSERT(fixed == 1);
79
80 if (!(collation.collation->state & MY_CS_NONASCII))
81 {
82 String *res= val_str_ascii(str);
83 if (res)
84 res->set_charset(collation.collation);
85 return res;
86 }
87
88 DBUG_ASSERT(str != ascii_buffer);
89
90 uint errors;
91 String *res= val_str_ascii(ascii_buffer);
92 if (!res)
93 return 0;
94
95 if ((null_value= str->copy(res->ptr(), res->length(),
96 &my_charset_latin1, collation.collation,
97 &errors)))
98 return 0;
99
100 return str;
101}
102
103
104bool Item_str_func::fix_fields(THD *thd, Item **ref)
105{
106 bool res= Item_func::fix_fields(thd, ref);
107 /*
108 In Item_str_func::check_well_formed_result() we may set null_value
109 flag on the same condition as in test() below.
110 */
111 maybe_null= maybe_null || thd->is_strict_mode();
112 return res;
113}
114
115
116my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
117{
118 DBUG_ASSERT(fixed == 1);
119 StringBuffer<64> tmp;
120 String *res= val_str(&tmp);
121 return res ? decimal_from_string_with_check(decimal_value, res) : 0;
122}
123
124
125double Item_str_func::val_real()
126{
127 DBUG_ASSERT(fixed == 1);
128 StringBuffer<64> tmp;
129 String *res= val_str(&tmp);
130 return res ? double_from_string_with_check(res) : 0.0;
131}
132
133
134longlong Item_str_func::val_int()
135{
136 DBUG_ASSERT(fixed == 1);
137 StringBuffer<22> tmp;
138 String *res= val_str(&tmp);
139 return res ? longlong_from_string_with_check(res) : 0;
140}
141
142
143String *Item_func_md5::val_str_ascii(String *str)
144{
145 DBUG_ASSERT(fixed == 1);
146 String * sptr= args[0]->val_str(str);
147 if (sptr)
148 {
149 uchar digest[16];
150
151 null_value=0;
152 compute_md5_hash(digest, (const char *) sptr->ptr(), sptr->length());
153 if (str->alloc(32)) // Ensure that memory is free
154 {
155 null_value=1;
156 return 0;
157 }
158 array_to_hex((char *) str->ptr(), digest, 16);
159 str->set_charset(&my_charset_numeric);
160 str->length((uint) 32);
161 return str;
162 }
163 null_value=1;
164 return 0;
165}
166
167
168String *Item_func_sha::val_str_ascii(String *str)
169{
170 DBUG_ASSERT(fixed == 1);
171 String * sptr= args[0]->val_str(str);
172 if (sptr) /* If we got value different from NULL */
173 {
174 /* Temporary buffer to store 160bit digest */
175 uint8 digest[MY_SHA1_HASH_SIZE];
176 my_sha1(digest, (const char *) sptr->ptr(), sptr->length());
177 /* Ensure that memory is free and we got result */
178 if (!str->alloc(MY_SHA1_HASH_SIZE*2))
179 {
180 array_to_hex((char *) str->ptr(), digest, MY_SHA1_HASH_SIZE);
181 str->set_charset(&my_charset_numeric);
182 str->length((uint) MY_SHA1_HASH_SIZE*2);
183 null_value=0;
184 return str;
185 }
186 }
187 null_value=1;
188 return 0;
189}
190
191void Item_func_sha::fix_length_and_dec()
192{
193 // size of hex representation of hash
194 fix_length_and_charset(MY_SHA1_HASH_SIZE * 2, default_charset());
195}
196
197String *Item_func_sha2::val_str_ascii(String *str)
198{
199 DBUG_ASSERT(fixed == 1);
200 unsigned char digest_buf[512/8]; // enough for SHA512
201 String *input_string;
202 const char *input_ptr;
203 size_t input_len;
204
205 input_string= args[0]->val_str(str);
206 str->set_charset(&my_charset_bin);
207
208 if (input_string == NULL)
209 {
210 null_value= TRUE;
211 return (String *) NULL;
212 }
213
214 null_value= args[0]->null_value;
215 if (null_value)
216 return (String *) NULL;
217
218 input_ptr= input_string->ptr();
219 input_len= input_string->length();
220
221 longlong digest_length= args[1]->val_int();
222 switch (digest_length) {
223 case 512:
224 my_sha512(digest_buf, input_ptr, input_len);
225 break;
226 case 384:
227 my_sha384(digest_buf, input_ptr, input_len);
228 break;
229 case 224:
230 my_sha224(digest_buf, input_ptr, input_len);
231 break;
232 case 0: // SHA-256 is the default
233 digest_length= 256;
234 /* fall through */
235 case 256:
236 my_sha256(digest_buf, input_ptr, input_len);
237 break;
238 default:
239 if (!args[1]->const_item())
240 {
241 THD *thd= current_thd;
242 push_warning_printf(thd,
243 Sql_condition::WARN_LEVEL_WARN,
244 ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
245 ER_THD(thd, ER_WRONG_PARAMETERS_TO_NATIVE_FCT),
246 "sha2");
247 }
248 null_value= TRUE;
249 return NULL;
250 }
251 digest_length/= 8; /* bits to bytes */
252
253 /*
254 Since we're subverting the usual String methods, we must make sure that
255 the destination has space for the bytes we're about to write.
256 */
257 str->realloc((uint) digest_length*2 + 1); /* Each byte as two nybbles */
258
259 /* Convert the large number to a string-hex representation. */
260 array_to_hex((char *) str->ptr(), digest_buf, (uint)digest_length);
261
262 /* We poked raw bytes in. We must inform the the String of its length. */
263 str->length((uint) digest_length*2); /* Each byte as two nybbles */
264
265 null_value= FALSE;
266 return str;
267}
268
269
270void Item_func_sha2::fix_length_and_dec()
271{
272 maybe_null= 1;
273 max_length = 0;
274
275 int sha_variant= (int)(args[1]->const_item() ? args[1]->val_int() : 512);
276
277 switch (sha_variant) {
278 case 0: // SHA-256 is the default
279 sha_variant= 256;
280 /* fall through */
281 case 512:
282 case 384:
283 case 256:
284 case 224:
285 fix_length_and_charset(sha_variant/8 * 2, default_charset());
286 break;
287 default:
288 THD *thd= current_thd;
289 push_warning_printf(thd,
290 Sql_condition::WARN_LEVEL_WARN,
291 ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
292 ER_THD(thd, ER_WRONG_PARAMETERS_TO_NATIVE_FCT),
293 "sha2");
294 }
295}
296
297/* Implementation of AES encryption routines */
298void Item_aes_crypt::create_key(String *user_key, uchar *real_key)
299{
300 uchar *real_key_end= real_key + AES_KEY_LENGTH / 8;
301 uchar *ptr;
302 const char *sptr= user_key->ptr();
303 const char *key_end= sptr + user_key->length();
304
305 bzero(real_key, AES_KEY_LENGTH / 8);
306
307 for (ptr= real_key; sptr < key_end; ptr++, sptr++)
308 {
309 if (ptr == real_key_end)
310 ptr= real_key;
311 *ptr ^= (uchar) *sptr;
312 }
313}
314
315
316String *Item_aes_crypt::val_str(String *str2)
317{
318 DBUG_ASSERT(fixed == 1);
319 StringBuffer<80> user_key_buf;
320 String *sptr= args[0]->val_str(&tmp_value);
321 String *user_key= args[1]->val_str(&user_key_buf);
322 uint32 aes_length;
323
324 if (sptr && user_key) // we need both arguments to be not NULL
325 {
326 null_value=0;
327 aes_length=my_aes_get_size(MY_AES_ECB, sptr->length());
328
329 if (!str2->alloc(aes_length)) // Ensure that memory is free
330 {
331 uchar rkey[AES_KEY_LENGTH / 8];
332 create_key(user_key, rkey);
333
334 if (!my_aes_crypt(MY_AES_ECB, what, (uchar*)sptr->ptr(), sptr->length(),
335 (uchar*)str2->ptr(), &aes_length,
336 rkey, AES_KEY_LENGTH / 8, 0, 0))
337 {
338 str2->length((uint) aes_length);
339 return str2;
340 }
341 }
342 }
343 null_value=1;
344 return 0;
345}
346
347void Item_func_aes_encrypt::fix_length_and_dec()
348{
349 max_length=my_aes_get_size(MY_AES_ECB, args[0]->max_length);
350 what= ENCRYPTION_FLAG_ENCRYPT;
351}
352
353
354
355void Item_func_aes_decrypt::fix_length_and_dec()
356{
357 max_length=args[0]->max_length;
358 maybe_null= 1;
359 what= ENCRYPTION_FLAG_DECRYPT;
360}
361
362
363void Item_func_to_base64::fix_length_and_dec()
364{
365 maybe_null= args[0]->maybe_null;
366 collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
367 if (args[0]->max_length > (uint) my_base64_encode_max_arg_length())
368 {
369 maybe_null= 1;
370 fix_char_length_ulonglong((ulonglong) my_base64_encode_max_arg_length());
371 }
372 else
373 {
374 int length= my_base64_needed_encoded_length((int) args[0]->max_length);
375 DBUG_ASSERT(length > 0);
376 fix_char_length_ulonglong((ulonglong) length - 1);
377 }
378}
379
380
381String *Item_func_to_base64::val_str_ascii(String *str)
382{
383 String *res= args[0]->val_str(&tmp_value);
384 bool too_long= false;
385 int length;
386 if (!res ||
387 res->length() > (uint) my_base64_encode_max_arg_length() ||
388 (too_long=
389 ((uint) (length= my_base64_needed_encoded_length((int) res->length())) >
390 current_thd->variables.max_allowed_packet)) ||
391 str->alloc((uint) length))
392 {
393 null_value= 1; // NULL input, too long input, or OOM.
394 if (too_long)
395 {
396 THD *thd= current_thd;
397 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
398 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
399 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
400 func_name(),
401 thd->variables.max_allowed_packet);
402 }
403 return 0;
404 }
405 my_base64_encode(res->ptr(), (int) res->length(), (char*) str->ptr());
406 DBUG_ASSERT(length > 0);
407 str->length((uint) length - 1); // Without trailing '\0'
408 null_value= 0;
409 return str;
410}
411
412
413void Item_func_from_base64::fix_length_and_dec()
414{
415 if (args[0]->max_length > (uint) my_base64_decode_max_arg_length())
416 {
417 fix_char_length_ulonglong((ulonglong) my_base64_decode_max_arg_length());
418 }
419 else
420 {
421 int length= my_base64_needed_decoded_length((int) args[0]->max_length);
422 fix_char_length_ulonglong((ulonglong) length);
423 }
424 maybe_null= 1; // Can be NULL, e.g. in case of badly formed input string
425}
426
427
428String *Item_func_from_base64::val_str(String *str)
429{
430 String *res= args[0]->val_str_ascii(&tmp_value);
431 int length;
432 const char *end_ptr;
433
434 if (!res)
435 goto err;
436
437 if (res->length() > (uint) my_base64_decode_max_arg_length() ||
438 ((uint) (length= my_base64_needed_decoded_length((int) res->length())) >
439 current_thd->variables.max_allowed_packet))
440 {
441 THD *thd= current_thd;
442 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
443 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
444 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
445 func_name(),
446 thd->variables.max_allowed_packet);
447 goto err;
448 }
449
450 if (str->alloc((uint) length))
451 goto err;
452
453 if ((length= my_base64_decode(res->ptr(), (int) res->length(),
454 (char *) str->ptr(), &end_ptr, 0)) < 0 ||
455 end_ptr < res->ptr() + res->length())
456 {
457 THD *thd= current_thd;
458 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
459 ER_BAD_BASE64_DATA, ER_THD(thd, ER_BAD_BASE64_DATA),
460 (int) (end_ptr - res->ptr()));
461 goto err;
462 }
463
464 str->length((uint) length);
465 null_value= 0;
466 return str;
467err:
468 null_value= 1; // NULL input, too long input, OOM, or badly formed input
469 return 0;
470}
471///////////////////////////////////////////////////////////////////////////////
472
473
474const char *histogram_types[] =
475 {"SINGLE_PREC_HB", "DOUBLE_PREC_HB", 0};
476static TYPELIB hystorgam_types_typelib=
477 { array_elements(histogram_types),
478 "histogram_types",
479 histogram_types, NULL};
480const char *representation_by_type[]= {"%.3f", "%.5f"};
481
482String *Item_func_decode_histogram::val_str(String *str)
483{
484 DBUG_ASSERT(fixed == 1);
485 char buff[STRING_BUFFER_USUAL_SIZE];
486 String *res, tmp(buff, sizeof(buff), &my_charset_bin);
487 int type;
488
489 tmp.length(0);
490 if (!(res= args[0]->val_str(&tmp)) ||
491 (type= find_type(res->c_ptr_safe(),
492 &hystorgam_types_typelib, MYF(0))) <= 0)
493 {
494 null_value= 1;
495 return 0;
496 }
497 type--;
498
499 tmp.length(0);
500 if (!(res= args[1]->val_str(&tmp)))
501 {
502 null_value= 1;
503 return 0;
504 }
505 if (type == DOUBLE_PREC_HB && res->length() % 2 != 0)
506 res->length(res->length() - 1); // one byte is unused
507
508 double prev= 0.0;
509 uint i;
510 str->length(0);
511 char numbuf[32];
512 const uchar *p= (uchar*)res->c_ptr_safe();
513 for (i= 0; i < res->length(); i++)
514 {
515 double val;
516 switch (type)
517 {
518 case SINGLE_PREC_HB:
519 val= p[i] / ((double)((1 << 8) - 1));
520 break;
521 case DOUBLE_PREC_HB:
522 val= uint2korr(p + i) / ((double)((1 << 16) - 1));
523 i++;
524 break;
525 default:
526 val= 0;
527 DBUG_ASSERT(0);
528 }
529 /* show delta with previous value */
530 size_t size= my_snprintf(numbuf, sizeof(numbuf),
531 representation_by_type[type], val - prev);
532 str->append(numbuf, size);
533 str->append(",");
534 prev= val;
535 }
536 /* show delta with max */
537 size_t size= my_snprintf(numbuf, sizeof(numbuf),
538 representation_by_type[type], 1.0 - prev);
539 str->append(numbuf, size);
540
541 null_value=0;
542 return str;
543}
544
545
546///////////////////////////////////////////////////////////////////////////////
547
548/*
549 Realloc the result buffer.
550 NOTE: We should be prudent in the initial allocation unit -- the
551 size of the arguments is a function of data distribution, which
552 can be any. Instead of overcommitting at the first row, we grow
553 the allocated amount by the factor of 2. This ensures that no
554 more than 25% of memory will be overcommitted on average.
555
556 @param IN/OUT str - the result string
557 @param IN length - new total space required in "str"
558 @retval false - on success
559 @retval true - on error
560*/
561
562bool Item_func_concat::realloc_result(String *str, uint length) const
563{
564 if (str->alloced_length() >= length)
565 return false; // Alloced space is big enough, nothing to do.
566
567 if (str->alloced_length() == 0)
568 return str->alloc(length);
569
570 /*
571 Item_func_concat::val_str() makes sure the result length does not grow
572 higher than max_allowed_packet. So "length" is limited to 1G here.
573 We can't say anything about the current value of str->alloced_length(),
574 as str was initially set by args[0]->val_str(str).
575 So multiplication by 2 can overflow, if args[0] for some reasons
576 did not limit the result to max_alloced_packet. But it's not harmful,
577 "str" will be realloced exactly to "length" bytes in case of overflow.
578 */
579 uint new_length= MY_MAX(str->alloced_length() * 2, length);
580 return str->realloc(new_length);
581}
582
583
584/**
585 Concatenate args with the following premises:
586 If only one arg (which is ok), return value of arg;
587*/
588
589String *Item_func_concat::val_str(String *str)
590{
591 DBUG_ASSERT(fixed == 1);
592 THD *thd= current_thd;
593 String *res;
594
595 null_value=0;
596 if (!(res= args[0]->val_str(str)))
597 goto null;
598
599 if (res != str)
600 str->copy(res->ptr(), res->length(), res->charset());
601
602 for (uint i= 1 ; i < arg_count ; i++)
603 {
604 if (!(res= args[i]->val_str(&tmp_value)) ||
605 append_value(thd, str, res))
606 goto null;
607 }
608
609 str->set_charset(collation.collation);
610 return str;
611
612null:
613 null_value= true;
614 return 0;
615}
616
617
618String *Item_func_concat_operator_oracle::val_str(String *str)
619{
620 DBUG_ASSERT(fixed == 1);
621 THD *thd= current_thd;
622 String *res;
623 uint i;
624
625 null_value=0;
626 // Search first non null argument
627 for (i= 0; i < arg_count; i++)
628 {
629 if ((res= args[i]->val_str(str)))
630 break;
631 }
632 if (i == arg_count)
633 goto null;
634
635 if (res != str)
636 str->copy(res->ptr(), res->length(), res->charset());
637
638 for (i++ ; i < arg_count ; i++)
639 {
640 if (!(res= args[i]->val_str(&tmp_value)) || res->length() == 0)
641 continue;
642 if (append_value(thd, str, res))
643 goto null;
644 }
645
646 str->set_charset(collation.collation);
647 return str;
648
649null:
650 null_value= true;
651 return 0;
652}
653
654
655bool Item_func_concat::append_value(THD *thd, String *res, const String *app)
656{
657 uint concat_len;
658 if ((concat_len= res->length() + app->length()) >
659 thd->variables.max_allowed_packet)
660 {
661 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
662 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
663 ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
664 thd->variables.max_allowed_packet);
665 return true;
666 }
667 DBUG_ASSERT(!res->uses_buffer_owned_by(app));
668 DBUG_ASSERT(!app->uses_buffer_owned_by(res));
669 return realloc_result(res, concat_len) || res->append(*app);
670}
671
672
673void Item_func_concat::fix_length_and_dec()
674{
675 ulonglong char_length= 0;
676
677 if (agg_arg_charsets_for_string_result(collation, args, arg_count))
678 return;
679
680 for (uint i=0 ; i < arg_count ; i++)
681 char_length+= args[i]->max_char_length();
682
683 fix_char_length_ulonglong(char_length);
684}
685
686/**
687 @details
688 Function des_encrypt() by tonu@spam.ee & monty
689 Works only if compiled with OpenSSL library support.
690 @return
691 A binary string where first character is CHAR(128 | key-number).
692 If one uses a string key key_number is 127.
693 Encryption result is longer than original by formula:
694 @code new_length= org_length + (8-(org_length % 8))+1 @endcode
695*/
696
697String *Item_func_des_encrypt::val_str(String *str)
698{
699 DBUG_ASSERT(fixed == 1);
700#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
701 uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
702 DES_cblock ivec;
703 struct st_des_keyblock keyblock;
704 struct st_des_keyschedule keyschedule;
705 const char *append_str="********";
706 uint key_number, res_length, tail;
707 String *res= args[0]->val_str(&tmp_value);
708
709 if ((null_value= args[0]->null_value))
710 return 0; // ENCRYPT(NULL) == NULL
711 if ((res_length=res->length()) == 0)
712 return make_empty_result();
713 if (arg_count == 1)
714 {
715 /* Protect against someone doing FLUSH DES_KEY_FILE */
716 mysql_mutex_lock(&LOCK_des_key_file);
717 keyschedule= des_keyschedule[key_number=des_default_key];
718 mysql_mutex_unlock(&LOCK_des_key_file);
719 }
720 else if (args[1]->result_type() == INT_RESULT)
721 {
722 key_number= (uint) args[1]->val_int();
723 if (key_number > 9)
724 goto error;
725 mysql_mutex_lock(&LOCK_des_key_file);
726 keyschedule= des_keyschedule[key_number];
727 mysql_mutex_unlock(&LOCK_des_key_file);
728 }
729 else
730 {
731 String *keystr= args[1]->val_str(str);
732 if (!keystr)
733 goto error;
734 key_number=127; // User key string
735
736 /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */
737 bzero((char*) &ivec,sizeof(ivec));
738 if (!EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
739 (uchar*) keystr->ptr(), (int) keystr->length(),
740 1, (uchar*) &keyblock,ivec))
741 goto error;
742 DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
743 DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
744 DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
745 }
746
747 /*
748 The problem: DES algorithm requires original data to be in 8-bytes
749 chunks. Missing bytes get filled with '*'s and result of encryption
750 can be up to 8 bytes longer than original string. When decrypted,
751 we do not know the size of original string :(
752 We add one byte with value 0x1..0x8 as the last byte of the padded
753 string marking change of string length.
754 */
755
756 tail= 8 - (res_length % 8); // 1..8 marking extra length
757 res_length+=tail;
758 if (tmp_arg.realloc(res_length))
759 goto error;
760 tmp_arg.length(0);
761 tmp_arg.append(res->ptr(), res->length());
762 code= ER_OUT_OF_RESOURCES;
763 if (tmp_arg.append(append_str, tail) || str->alloc(res_length+1))
764 goto error;
765 tmp_arg[res_length-1]=tail; // save extra length
766 str->realloc(res_length+1);
767 str->length(res_length+1);
768 str->set_charset(&my_charset_bin);
769 (*str)[0]=(char) (128 | key_number);
770 // Real encryption
771 bzero((char*) &ivec,sizeof(ivec));
772 DES_ede3_cbc_encrypt((const uchar*) (tmp_arg.ptr()),
773 (uchar*) (str->ptr()+1),
774 res_length,
775 &keyschedule.ks1,
776 &keyschedule.ks2,
777 &keyschedule.ks3,
778 &ivec, TRUE);
779 return str;
780
781error:
782 THD *thd= current_thd;
783 push_warning_printf(thd,Sql_condition::WARN_LEVEL_WARN,
784 code, ER_THD(thd, code),
785 "des_encrypt");
786#else
787 THD *thd= current_thd;
788 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
789 ER_FEATURE_DISABLED, ER_THD(thd, ER_FEATURE_DISABLED),
790 "des_encrypt", "--with-ssl");
791#endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
792 null_value=1;
793 return 0;
794}
795
796
797String *Item_func_des_decrypt::val_str(String *str)
798{
799 DBUG_ASSERT(fixed == 1);
800#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
801 uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
802 DES_cblock ivec;
803 struct st_des_keyblock keyblock;
804 struct st_des_keyschedule keyschedule;
805 String *res= args[0]->val_str(&tmp_value);
806 uint length,tail;
807
808 if ((null_value= args[0]->null_value))
809 return 0;
810 length= res->length();
811 if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128))
812 return res; // Skip decryption if not encrypted
813
814 if (arg_count == 1) // If automatic uncompression
815 {
816 uint key_number=(uint) (*res)[0] & 127;
817 // Check if automatic key and that we have privilege to uncompress using it
818 if (!(current_thd->security_ctx->master_access & SUPER_ACL) ||
819 key_number > 9)
820 goto error;
821
822 mysql_mutex_lock(&LOCK_des_key_file);
823 keyschedule= des_keyschedule[key_number];
824 mysql_mutex_unlock(&LOCK_des_key_file);
825 }
826 else
827 {
828 // We make good 24-byte (168 bit) key from given plaintext key with MD5
829 String *keystr= args[1]->val_str(str);
830 if (!keystr)
831 goto error;
832
833 bzero((char*) &ivec,sizeof(ivec));
834 if (!EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
835 (uchar*) keystr->ptr(),(int) keystr->length(),
836 1,(uchar*) &keyblock,ivec))
837 goto error;
838 // Here we set all 64-bit keys (56 effective) one by one
839 DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
840 DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
841 DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
842 }
843 code= ER_OUT_OF_RESOURCES;
844 if (str->alloc(length-1))
845 goto error;
846
847 bzero((char*) &ivec,sizeof(ivec));
848 DES_ede3_cbc_encrypt((const uchar*) res->ptr()+1,
849 (uchar*) (str->ptr()),
850 length-1,
851 &keyschedule.ks1,
852 &keyschedule.ks2,
853 &keyschedule.ks3,
854 &ivec, FALSE);
855 /* Restore old length of key */
856 if ((tail=(uint) (uchar) (*str)[length-2]) > 8)
857 goto wrong_key; // Wrong key
858 str->length(length-1-tail);
859 str->set_charset(&my_charset_bin);
860 return str;
861
862error:
863 {
864 THD *thd= current_thd;
865 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
866 code, ER_THD(thd, code),
867 "des_decrypt");
868 }
869wrong_key:
870#else
871 {
872 THD *thd= current_thd;
873 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
874 ER_FEATURE_DISABLED, ER_THD(thd, ER_FEATURE_DISABLED),
875 "des_decrypt", "--with-ssl");
876 }
877#endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
878 null_value=1;
879 return 0;
880}
881
882
883/**
884 concat with separator. First arg is the separator
885 concat_ws takes at least two arguments.
886*/
887
888String *Item_func_concat_ws::val_str(String *str)
889{
890 DBUG_ASSERT(fixed == 1);
891 char tmp_str_buff[10];
892 String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
893 *sep_str, *res, *res2,*use_as_buff;
894 uint i;
895 bool is_const= 0;
896 THD *thd= 0;
897
898 null_value=0;
899 if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
900 goto null;
901
902 use_as_buff= &tmp_value;
903 str->length(0); // QQ; Should be removed
904 res=str; // If 0 arg_count
905
906 // Skip until non-null argument is found.
907 // If not, return the empty string
908 for (i=1; i < arg_count; i++)
909 if ((res= args[i]->val_str(str)))
910 {
911 is_const= args[i]->const_item();
912 break;
913 }
914
915 if (i == arg_count)
916 return make_empty_result();
917
918 for (i++; i < arg_count ; i++)
919 {
920 if (!(res2= args[i]->val_str(use_as_buff)))
921 continue; // Skip NULL
922
923 if (!thd)
924 thd= current_thd;
925 if (res->length() + sep_str->length() + res2->length() >
926 thd->variables.max_allowed_packet)
927 {
928 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
929 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
930 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
931 func_name(),
932 thd->variables.max_allowed_packet);
933 goto null;
934 }
935 if (!is_const && res->alloced_length() >=
936 res->length() + sep_str->length() + res2->length())
937 { // Use old buffer
938 res->append(*sep_str); // res->length() > 0 always
939 res->append(*res2);
940 }
941 else if (str->alloced_length() >=
942 res->length() + sep_str->length() + res2->length())
943 {
944 /* We have room in str; We can't get any errors here */
945 if (str->ptr() == res2->ptr())
946 { // This is quite uncommon!
947 str->replace(0,0,*sep_str);
948 str->replace(0,0,*res);
949 }
950 else
951 {
952 str->copy(*res);
953 str->append(*sep_str);
954 str->append(*res2);
955 }
956 res=str;
957 use_as_buff= &tmp_value;
958 }
959 else if (res == &tmp_value)
960 {
961 if (res->append(*sep_str) || res->append(*res2))
962 goto null; // Must be a blob
963 }
964 else if (res2 == &tmp_value)
965 { // This can happend only 1 time
966 if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res))
967 goto null;
968 res= &tmp_value;
969 use_as_buff=str; // Put next arg here
970 }
971 else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
972 res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
973 {
974 /*
975 This happens really seldom:
976 In this case res2 is sub string of tmp_value. We will
977 now work in place in tmp_value to set it to res | sep_str | res2
978 */
979 /* Chop the last characters in tmp_value that isn't in res2 */
980 tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
981 res2->length());
982 /* Place res2 at start of tmp_value, remove chars before res2 */
983 if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
984 *res) ||
985 tmp_value.replace(res->length(),0, *sep_str))
986 goto null;
987 res= &tmp_value;
988 use_as_buff=str; // Put next arg here
989 }
990 else
991 { // Two big const strings
992 /*
993 NOTE: We should be prudent in the initial allocation unit -- the
994 size of the arguments is a function of data distribution, which can
995 be any. Instead of overcommitting at the first row, we grow the
996 allocated amount by the factor of 2. This ensures that no more than
997 25% of memory will be overcommitted on average.
998 */
999
1000 uint concat_len= res->length() + sep_str->length() + res2->length();
1001
1002 if (tmp_value.alloced_length() < concat_len)
1003 {
1004 if (tmp_value.alloced_length() == 0)
1005 {
1006 if (tmp_value.alloc(concat_len))
1007 goto null;
1008 }
1009 else
1010 {
1011 uint new_len = MY_MAX(tmp_value.alloced_length() * 2, concat_len);
1012
1013 if (tmp_value.realloc(new_len))
1014 goto null;
1015 }
1016 }
1017
1018 if (tmp_value.copy(*res) ||
1019 tmp_value.append(*sep_str) ||
1020 tmp_value.append(*res2))
1021 goto null;
1022 res= &tmp_value;
1023 use_as_buff=str;
1024 }
1025 }
1026 res->set_charset(collation.collation);
1027 return res;
1028
1029null:
1030 null_value=1;
1031 return 0;
1032}
1033
1034
1035void Item_func_concat_ws::fix_length_and_dec()
1036{
1037 ulonglong char_length;
1038
1039 if (agg_arg_charsets_for_string_result(collation, args, arg_count))
1040 return;
1041
1042 /*
1043 arg_count cannot be less than 2,
1044 it is done on parser level in sql_yacc.yy
1045 so, (arg_count - 2) is safe here.
1046 */
1047 char_length= (ulonglong) args[0]->max_char_length() * (arg_count - 2);
1048 for (uint i=1 ; i < arg_count ; i++)
1049 char_length+= args[i]->max_char_length();
1050
1051 fix_char_length_ulonglong(char_length);
1052}
1053
1054
1055String *Item_func_reverse::val_str(String *str)
1056{
1057 DBUG_ASSERT(fixed == 1);
1058 String *res= args[0]->val_str(&tmp_value);
1059 const char *ptr, *end;
1060 char *tmp;
1061
1062 if ((null_value=args[0]->null_value))
1063 return 0;
1064 /* An empty string is a special case as the string pointer may be null */
1065 if (!res->length())
1066 return make_empty_result();
1067 if (str->alloced_length() < res->length() &&
1068 str->realloc(res->length()))
1069 {
1070 null_value= 1;
1071 return 0;
1072 }
1073 str->length(res->length());
1074 str->set_charset(res->charset());
1075 ptr= res->ptr();
1076 end= res->end();
1077 tmp= (char *) str->end();
1078#ifdef USE_MB
1079 if (use_mb(res->charset()))
1080 {
1081 uint32 l;
1082 while (ptr < end)
1083 {
1084 if ((l= my_ismbchar(res->charset(),ptr,end)))
1085 {
1086 tmp-= l;
1087 DBUG_ASSERT(tmp >= str->ptr());
1088 memcpy(tmp,ptr,l);
1089 ptr+= l;
1090 }
1091 else
1092 *--tmp= *ptr++;
1093 }
1094 }
1095 else
1096#endif /* USE_MB */
1097 {
1098 while (ptr < end)
1099 *--tmp= *ptr++;
1100 }
1101 return str;
1102}
1103
1104
1105void Item_func_reverse::fix_length_and_dec()
1106{
1107 agg_arg_charsets_for_string_result(collation, args, 1);
1108 DBUG_ASSERT(collation.collation != NULL);
1109 fix_char_length(args[0]->max_char_length());
1110}
1111
1112/**
1113 Replace all occurences of string2 in string1 with string3.
1114
1115 Don't reallocate val_str() if not needed.
1116
1117 @todo
1118 Fix that this works with binary strings when using USE_MB
1119*/
1120
1121String *Item_func_replace::val_str_internal(String *str,
1122 String *empty_string_for_null)
1123{
1124 DBUG_ASSERT(fixed == 1);
1125 String *res,*res2,*res3;
1126 int offset;
1127 uint from_length,to_length;
1128 bool alloced=0;
1129#ifdef USE_MB
1130 const char *ptr,*end,*strend,*search,*search_end;
1131 uint32 l;
1132 bool binary_cmp;
1133#endif
1134 THD *thd= 0;
1135
1136 null_value=0;
1137 res=args[0]->val_str(str);
1138 if (args[0]->null_value)
1139 goto null;
1140 res2=args[1]->val_str(&tmp_value);
1141 if (args[1]->null_value)
1142 {
1143 if (!empty_string_for_null)
1144 goto null;
1145 res2= empty_string_for_null;
1146 }
1147 res->set_charset(collation.collation);
1148
1149#ifdef USE_MB
1150 binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
1151#endif
1152
1153 if (res2->length() == 0)
1154 return res;
1155#ifndef USE_MB
1156 if ((offset=res->strstr(*res2)) < 0)
1157 return res;
1158#else
1159 offset=0;
1160 if (binary_cmp && (offset=res->strstr(*res2)) < 0)
1161 return res;
1162#endif
1163 if (!(res3=args[2]->val_str(&tmp_value2)))
1164 {
1165 if (!empty_string_for_null)
1166 goto null;
1167 res3= empty_string_for_null;
1168 }
1169 from_length= res2->length();
1170 to_length= res3->length();
1171
1172#ifdef USE_MB
1173 if (!binary_cmp)
1174 {
1175 search=res2->ptr();
1176 search_end=search+from_length;
1177redo:
1178 DBUG_ASSERT(res->ptr() || !offset);
1179 ptr=res->ptr()+offset;
1180 strend=res->ptr()+res->length();
1181 /*
1182 In some cases val_str() can return empty string
1183 with ptr() == NULL and length() == 0.
1184 Let's check strend to avoid overflow.
1185 */
1186 end= strend ? strend - from_length + 1 : NULL;
1187 while (ptr < end)
1188 {
1189 if (*ptr == *search)
1190 {
1191 char *i,*j;
1192 i=(char*) ptr+1; j=(char*) search+1;
1193 while (j != search_end)
1194 if (*i++ != *j++) goto skip;
1195 offset= (int) (ptr-res->ptr());
1196
1197 if (!thd)
1198 thd= current_thd;
1199
1200 if (res->length()-from_length + to_length >
1201 thd->variables.max_allowed_packet)
1202 {
1203 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1204 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1205 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1206 func_name(),
1207 thd->variables.max_allowed_packet);
1208
1209 goto null;
1210 }
1211 if (!alloced)
1212 {
1213 alloced=1;
1214 res=copy_if_not_alloced(str,res,res->length()+to_length);
1215 }
1216 res->replace((uint) offset,from_length,*res3);
1217 offset+=(int) to_length;
1218 goto redo;
1219 }
1220 skip:
1221 if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
1222 else ++ptr;
1223 }
1224 }
1225 else
1226#endif /* USE_MB */
1227 {
1228 thd= current_thd;
1229 do
1230 {
1231 if (res->length()-from_length + to_length >
1232 thd->variables.max_allowed_packet)
1233 {
1234 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1235 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1236 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1237 func_name(),
1238 thd->variables.max_allowed_packet);
1239 goto null;
1240 }
1241 if (!alloced)
1242 {
1243 alloced=1;
1244 res=copy_if_not_alloced(str,res,res->length()+to_length);
1245 }
1246 res->replace((uint) offset,from_length,*res3);
1247 offset+=(int) to_length;
1248 }
1249 while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
1250 }
1251 if (empty_string_for_null && !res->length())
1252 goto null;
1253
1254 return res;
1255
1256null:
1257 null_value=1;
1258 return 0;
1259}
1260
1261
1262void Item_func_replace::fix_length_and_dec()
1263{
1264 ulonglong char_length= (ulonglong) args[0]->max_char_length();
1265 int diff=(int) (args[2]->max_char_length() - args[1]->max_char_length());
1266 if (diff > 0 && args[1]->max_char_length())
1267 { // Calculate of maxreplaces
1268 ulonglong max_substrs= char_length / args[1]->max_char_length();
1269 char_length+= max_substrs * (uint) diff;
1270 }
1271
1272 if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 3))
1273 return;
1274 fix_char_length_ulonglong(char_length);
1275}
1276
1277
1278/*********************************************************************/
1279bool Item_func_regexp_replace::fix_fields(THD *thd, Item **ref)
1280{
1281 re.set_recursion_limit(thd);
1282 return Item_str_func::fix_fields(thd, ref);
1283}
1284
1285
1286void Item_func_regexp_replace::fix_length_and_dec()
1287{
1288 if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 3))
1289 return;
1290 max_length= MAX_BLOB_WIDTH;
1291 re.init(collation.collation, 0);
1292 re.fix_owner(this, args[0], args[1]);
1293}
1294
1295
1296/*
1297 Traverse through the replacement string and append to "str".
1298 Sub-pattern references \0 .. \9 are recognized, which are replaced
1299 to the chunks of the source string.
1300*/
1301bool Item_func_regexp_replace::append_replacement(String *str,
1302 const LEX_CSTRING *source,
1303 const LEX_CSTRING *replace)
1304{
1305 const char *beg= replace->str;
1306 const char *end= beg + replace->length;
1307 CHARSET_INFO *cs= re.library_charset();
1308
1309 for ( ; ; )
1310 {
1311 my_wc_t wc;
1312 int cnv, n;
1313
1314 if ((cnv= cs->cset->mb_wc(cs, &wc, (const uchar *) beg,
1315 (const uchar *) end)) < 1)
1316 break; /* End of line */
1317 beg+= cnv;
1318
1319 if (wc != '\\')
1320 {
1321 if (str->append(beg - cnv, cnv, cs))
1322 return true;
1323 continue;
1324 }
1325
1326 if ((cnv= cs->cset->mb_wc(cs, &wc, (const uchar *) beg,
1327 (const uchar *) end)) < 1)
1328 break; /* End of line */
1329 beg+= cnv;
1330
1331 if ((n= ((int) wc) - '0') >= 0 && n <= 9)
1332 {
1333 if (n < re.nsubpatterns())
1334 {
1335 /* A valid sub-pattern reference found */
1336 int pbeg= re.subpattern_start(n), plength= re.subpattern_end(n) - pbeg;
1337 if (str->append(source->str + pbeg, plength, cs))
1338 return true;
1339 }
1340 }
1341 else
1342 {
1343 /*
1344 A non-digit character following after '\'.
1345 Just add the character itself.
1346 */
1347 if (str->append(beg - cnv, cnv, cs))
1348 return false;
1349 }
1350 }
1351 return false;
1352}
1353
1354
1355String *Item_func_regexp_replace::val_str(String *str)
1356{
1357 DBUG_ASSERT(fixed == 1);
1358 char buff0[MAX_FIELD_WIDTH];
1359 char buff2[MAX_FIELD_WIDTH];
1360 String tmp0(buff0,sizeof(buff0),&my_charset_bin);
1361 String tmp2(buff2,sizeof(buff2),&my_charset_bin);
1362 String *source= args[0]->val_str(&tmp0);
1363 String *replace= args[2]->val_str(&tmp2);
1364 LEX_CSTRING src, rpl;
1365 int startoffset= 0;
1366
1367 if ((null_value= (args[0]->null_value || args[2]->null_value ||
1368 re.recompile(args[1]))))
1369 return (String *) 0;
1370
1371 if (!(source= re.convert_if_needed(source, &re.subject_converter)) ||
1372 !(replace= re.convert_if_needed(replace, &re.replace_converter)))
1373 goto err;
1374
1375 src= source->lex_cstring();
1376 rpl= replace->lex_cstring();
1377
1378 str->length(0);
1379 str->set_charset(collation.collation);
1380
1381 for ( ; ; ) // Iterate through all matches
1382 {
1383
1384 if (re.exec(src.str, src.length, startoffset))
1385 goto err;
1386
1387 if (!re.match() || re.subpattern_length(0) == 0)
1388 {
1389 /*
1390 No match or an empty match.
1391 Append the rest of the source string
1392 starting from startoffset until the end of the source.
1393 */
1394 if (str->append(src.str + startoffset, src.length - startoffset, re.library_charset()))
1395 goto err;
1396 return str;
1397 }
1398
1399 /*
1400 Append prefix, the part before the matching pattern.
1401 starting from startoffset until the next match
1402 */
1403 if (str->append(src.str + startoffset, re.subpattern_start(0) - startoffset, re.library_charset()))
1404 goto err;
1405
1406 // Append replacement
1407 if (append_replacement(str, &src, &rpl))
1408 goto err;
1409
1410 // Set the new start point as the end of previous match
1411 startoffset= re.subpattern_end(0);
1412 }
1413 return str;
1414
1415err:
1416 null_value= true;
1417 return (String *) 0;
1418}
1419
1420
1421bool Item_func_regexp_substr::fix_fields(THD *thd, Item **ref)
1422{
1423 re.set_recursion_limit(thd);
1424 return Item_str_func::fix_fields(thd, ref);
1425}
1426
1427
1428void Item_func_regexp_substr::fix_length_and_dec()
1429{
1430 if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 2))
1431 return;
1432 fix_char_length(args[0]->max_char_length());
1433 re.init(collation.collation, 0);
1434 re.fix_owner(this, args[0], args[1]);
1435}
1436
1437
1438String *Item_func_regexp_substr::val_str(String *str)
1439{
1440 DBUG_ASSERT(fixed == 1);
1441 char buff0[MAX_FIELD_WIDTH];
1442 String tmp0(buff0,sizeof(buff0),&my_charset_bin);
1443 String *source= args[0]->val_str(&tmp0);
1444
1445 if ((null_value= (args[0]->null_value || re.recompile(args[1]))))
1446 return (String *) 0;
1447
1448 if (!(source= re.convert_if_needed(source, &re.subject_converter)))
1449 goto err;
1450
1451 str->length(0);
1452 str->set_charset(collation.collation);
1453
1454 if (re.exec(source->ptr(), source->length(), 0))
1455 goto err;
1456
1457 if (!re.match())
1458 return str;
1459
1460 if (str->append(source->ptr() + re.subpattern_start(0),
1461 re.subpattern_end(0) - re.subpattern_start(0),
1462 re.library_charset()))
1463 goto err;
1464
1465 return str;
1466
1467err:
1468 null_value= true;
1469 return (String *) 0;
1470}
1471
1472
1473/************************************************************************/
1474
1475
1476String *Item_func_insert::val_str(String *str)
1477{
1478 DBUG_ASSERT(fixed == 1);
1479 String *res,*res2;
1480 longlong start, length; /* must be longlong to avoid truncation */
1481
1482 null_value=0;
1483 res=args[0]->val_str(str);
1484 res2=args[3]->val_str(&tmp_value);
1485 start= args[1]->val_int() - 1;
1486 length= args[2]->val_int();
1487
1488 if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
1489 args[3]->null_value)
1490 goto null; /* purecov: inspected */
1491
1492 if ((start < 0) || (start > res->length()))
1493 return res; // Wrong param; skip insert
1494 if ((length < 0) || (length > res->length()))
1495 length= res->length();
1496
1497 /*
1498 There is one exception not handled (intentionaly) by the character set
1499 aggregation code. If one string is strong side and is binary, and
1500 another one is weak side and is a multi-byte character string,
1501 then we need to operate on the second string in terms on bytes when
1502 calling ::numchars() and ::charpos(), rather than in terms of characters.
1503 Lets substitute its character set to binary.
1504 */
1505 if (collation.collation == &my_charset_bin)
1506 {
1507 res->set_charset(&my_charset_bin);
1508 res2->set_charset(&my_charset_bin);
1509 }
1510
1511 /* start and length are now sufficiently valid to pass to charpos function */
1512 start= res->charpos((int) start);
1513 length= res->charpos((int) length, (uint32) start);
1514
1515 /* Re-testing with corrected params */
1516 if (start + 1 > res->length()) // remember, start = args[1].val_int() - 1
1517 return res; /* purecov: inspected */ // Wrong param; skip insert
1518 if (length > res->length() - start)
1519 length= res->length() - start;
1520
1521 {
1522 THD *thd= current_thd;
1523 if ((ulonglong) (res->length() - length + res2->length()) >
1524 (ulonglong) thd->variables.max_allowed_packet)
1525 {
1526 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1527 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1528 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1529 func_name(), thd->variables.max_allowed_packet);
1530 goto null;
1531 }
1532 }
1533 res=copy_if_not_alloced(str,res,res->length());
1534 res->replace((uint32) start,(uint32) length,*res2);
1535 return res;
1536null:
1537 null_value=1;
1538 return 0;
1539}
1540
1541
1542void Item_func_insert::fix_length_and_dec()
1543{
1544 ulonglong char_length;
1545
1546 // Handle character set for args[0] and args[3].
1547 if (agg_arg_charsets_for_string_result(collation, args, 2, 3))
1548 return;
1549 char_length= ((ulonglong) args[0]->max_char_length() +
1550 (ulonglong) args[3]->max_char_length());
1551 fix_char_length_ulonglong(char_length);
1552}
1553
1554
1555String *Item_str_conv::val_str(String *str)
1556{
1557 DBUG_ASSERT(fixed == 1);
1558 String *res;
1559 if (!(res=args[0]->val_str(str)))
1560 {
1561 null_value=1; /* purecov: inspected */
1562 return 0; /* purecov: inspected */
1563 }
1564 null_value=0;
1565 if (multiply == 1)
1566 {
1567 size_t len;
1568 res= copy_if_not_alloced(&tmp_value, res, res->length());
1569 len= converter(collation.collation, (char*) res->ptr(), res->length(),
1570 (char*) res->ptr(), res->length());
1571 DBUG_ASSERT(len <= res->length());
1572 res->length(len);
1573 }
1574 else
1575 {
1576 size_t len= res->length() * multiply;
1577 tmp_value.alloc(len);
1578 tmp_value.set_charset(collation.collation);
1579 len= converter(collation.collation, (char*) res->ptr(), res->length(),
1580 (char*) tmp_value.ptr(), len);
1581 tmp_value.length(len);
1582 res= &tmp_value;
1583 }
1584 return res;
1585}
1586
1587
1588void Item_func_lcase::fix_length_and_dec()
1589{
1590 agg_arg_charsets_for_string_result(collation, args, 1);
1591 DBUG_ASSERT(collation.collation != NULL);
1592 multiply= collation.collation->casedn_multiply;
1593 converter= collation.collation->cset->casedn;
1594 fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1595}
1596
1597void Item_func_ucase::fix_length_and_dec()
1598{
1599 agg_arg_charsets_for_string_result(collation, args, 1);
1600 DBUG_ASSERT(collation.collation != NULL);
1601 multiply= collation.collation->caseup_multiply;
1602 converter= collation.collation->cset->caseup;
1603 fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1604}
1605
1606
1607String *Item_func_left::val_str(String *str)
1608{
1609 DBUG_ASSERT(fixed == 1);
1610 String *res= args[0]->val_str(str);
1611
1612 /* must be longlong to avoid truncation */
1613 longlong length= args[1]->val_int();
1614 uint char_pos;
1615
1616 if ((null_value=(args[0]->null_value || args[1]->null_value)))
1617 return 0;
1618
1619 /* if "unsigned_flag" is set, we have a *huge* positive number. */
1620 if ((length <= 0) && (!args[1]->unsigned_flag))
1621 return make_empty_result();
1622 if ((res->length() <= (ulonglong) length) ||
1623 (res->length() <= (char_pos= res->charpos((int) length))))
1624 return res;
1625
1626 tmp_value.set(*res, 0, char_pos);
1627 return &tmp_value;
1628}
1629
1630
1631void Item_str_func::left_right_max_length()
1632{
1633 uint32 char_length= args[0]->max_char_length();
1634 if (args[1]->const_item())
1635 {
1636 int length= (int) args[1]->val_int();
1637 if (args[1]->null_value || length <= 0)
1638 char_length=0;
1639 else
1640 set_if_smaller(char_length, (uint) length);
1641 }
1642 fix_char_length(char_length);
1643}
1644
1645
1646void Item_func_left::fix_length_and_dec()
1647{
1648 agg_arg_charsets_for_string_result(collation, args, 1);
1649 DBUG_ASSERT(collation.collation != NULL);
1650 left_right_max_length();
1651}
1652
1653
1654String *Item_func_right::val_str(String *str)
1655{
1656 DBUG_ASSERT(fixed == 1);
1657 String *res= args[0]->val_str(str);
1658 /* must be longlong to avoid truncation */
1659 longlong length= args[1]->val_int();
1660
1661 if ((null_value=(args[0]->null_value || args[1]->null_value)))
1662 return 0; /* purecov: inspected */
1663
1664 /* if "unsigned_flag" is set, we have a *huge* positive number. */
1665 if ((length <= 0) && (!args[1]->unsigned_flag))
1666 return make_empty_result(); /* purecov: inspected */
1667
1668 if (res->length() <= (ulonglong) length)
1669 return res; /* purecov: inspected */
1670
1671 uint start=res->numchars();
1672 if (start <= (uint) length)
1673 return res;
1674 start=res->charpos(start - (uint) length);
1675 tmp_value.set(*res,start,res->length()-start);
1676 return &tmp_value;
1677}
1678
1679
1680void Item_func_right::fix_length_and_dec()
1681{
1682 agg_arg_charsets_for_string_result(collation, args, 1);
1683 DBUG_ASSERT(collation.collation != NULL);
1684 left_right_max_length();
1685}
1686
1687
1688String *Item_func_substr::val_str(String *str)
1689{
1690 DBUG_ASSERT(fixed == 1);
1691 String *res = args[0]->val_str(str);
1692 /* must be longlong to avoid truncation */
1693 longlong start= get_position();
1694 /* Assumes that the maximum length of a String is < INT_MAX32. */
1695 /* Limit so that code sees out-of-bound value properly. */
1696 longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
1697 longlong tmp_length;
1698
1699 if ((null_value=(args[0]->null_value || args[1]->null_value ||
1700 (arg_count == 3 && args[2]->null_value))))
1701 return 0; /* purecov: inspected */
1702
1703 /* Negative or zero length, will return empty string. */
1704 if ((arg_count == 3) && (length <= 0) &&
1705 (length == 0 || !args[2]->unsigned_flag))
1706 return make_empty_result();
1707
1708 /* Assumes that the maximum length of a String is < INT_MAX32. */
1709 /* Set here so that rest of code sees out-of-bound value as such. */
1710 if ((length <= 0) || (length > INT_MAX32))
1711 length= INT_MAX32;
1712
1713 /* if "unsigned_flag" is set, we have a *huge* positive number. */
1714 /* Assumes that the maximum length of a String is < INT_MAX32. */
1715 if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
1716 (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
1717 return make_empty_result();
1718
1719 start= ((start < 0) ? res->numchars() + start : start - 1);
1720 start= res->charpos((int) start);
1721 if ((start < 0) || ((uint) start + 1 > res->length()))
1722 return make_empty_result();
1723
1724 length= res->charpos((int) length, (uint32) start);
1725 tmp_length= res->length() - start;
1726 length= MY_MIN(length, tmp_length);
1727
1728 if (!start && (longlong) res->length() == length)
1729 return res;
1730 tmp_value.set(*res, (uint32) start, (uint32) length);
1731 return &tmp_value;
1732}
1733
1734
1735void Item_func_substr::fix_length_and_dec()
1736{
1737 max_length=args[0]->max_length;
1738
1739 agg_arg_charsets_for_string_result(collation, args, 1);
1740 DBUG_ASSERT(collation.collation != NULL);
1741 if (args[1]->const_item())
1742 {
1743 int32 start= (int32) get_position();
1744 if (args[1]->null_value)
1745 max_length= 0;
1746 else if (start < 0)
1747 max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start);
1748 else
1749 max_length-= MY_MIN((uint)(start - 1), max_length);
1750 }
1751 if (arg_count == 3 && args[2]->const_item())
1752 {
1753 int32 length= (int32) args[2]->val_int();
1754 if (args[2]->null_value || length <= 0)
1755 max_length=0; /* purecov: inspected */
1756 else
1757 set_if_smaller(max_length,(uint) length);
1758 }
1759 max_length*= collation.collation->mbmaxlen;
1760}
1761
1762
1763void Item_func_substr_index::fix_length_and_dec()
1764{
1765 if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 2))
1766 return;
1767 fix_char_length(args[0]->max_char_length());
1768}
1769
1770
1771String *Item_func_substr_index::val_str(String *str)
1772{
1773 DBUG_ASSERT(fixed == 1);
1774 char buff[MAX_FIELD_WIDTH];
1775 String tmp(buff,sizeof(buff),system_charset_info);
1776 String *res= args[0]->val_str(str);
1777 String *delimiter= args[1]->val_str(&tmp);
1778 int32 count= (int32) args[2]->val_int();
1779 uint offset;
1780
1781 if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
1782 { // string and/or delim are null
1783 null_value=1;
1784 return 0;
1785 }
1786 null_value=0;
1787 uint delimiter_length= delimiter->length();
1788 if (!res->length() || !delimiter_length || !count)
1789 return make_empty_result(); // Wrong parameters
1790
1791 res->set_charset(collation.collation);
1792
1793#ifdef USE_MB
1794 if (use_mb(res->charset()))
1795 {
1796 const char *ptr= res->ptr();
1797 const char *strend= ptr+res->length();
1798 const char *end= strend-delimiter_length+1;
1799 const char *search= delimiter->ptr();
1800 const char *search_end= search+delimiter_length;
1801 int32 n=0,c=count,pass;
1802 uint32 l;
1803 for (pass=(count>0);pass<2;++pass)
1804 {
1805 while (ptr < end)
1806 {
1807 if (*ptr == *search)
1808 {
1809 char *i,*j;
1810 i=(char*) ptr+1; j=(char*) search+1;
1811 while (j != search_end)
1812 if (*i++ != *j++) goto skip;
1813 if (pass==0) ++n;
1814 else if (!--c) break;
1815 ptr+= delimiter_length;
1816 continue;
1817 }
1818 skip:
1819 if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
1820 else ++ptr;
1821 } /* either not found or got total number when count<0 */
1822 if (pass == 0) /* count<0 */
1823 {
1824 c+=n+1;
1825 if (c<=0) return res; /* not found, return original string */
1826 ptr=res->ptr();
1827 }
1828 else
1829 {
1830 if (c) return res; /* Not found, return original string */
1831 if (count>0) /* return left part */
1832 {
1833 tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
1834 }
1835 else /* return right part */
1836 {
1837 ptr+= delimiter_length;
1838 tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
1839 }
1840 }
1841 }
1842 }
1843 else
1844#endif /* USE_MB */
1845 {
1846 if (count > 0)
1847 { // start counting from the beginning
1848 for (offset=0; ; offset+= delimiter_length)
1849 {
1850 if ((int) (offset= res->strstr(*delimiter, offset)) < 0)
1851 return res; // Didn't find, return org string
1852 if (!--count)
1853 {
1854 tmp_value.set(*res,0,offset);
1855 break;
1856 }
1857 }
1858 }
1859 else
1860 {
1861 /*
1862 Negative index, start counting at the end
1863 */
1864 for (offset=res->length(); offset ;)
1865 {
1866 /*
1867 this call will result in finding the position pointing to one
1868 address space less than where the found substring is located
1869 in res
1870 */
1871 if ((int) (offset= res->strrstr(*delimiter, offset)) < 0)
1872 return res; // Didn't find, return org string
1873 /*
1874 At this point, we've searched for the substring
1875 the number of times as supplied by the index value
1876 */
1877 if (!++count)
1878 {
1879 offset+= delimiter_length;
1880 tmp_value.set(*res,offset,res->length()- offset);
1881 break;
1882 }
1883 }
1884 if (count)
1885 return res; // Didn't find, return org string
1886 }
1887 }
1888 /*
1889 We always mark tmp_value as const so that if val_str() is called again
1890 on this object, we don't disrupt the contents of tmp_value when it was
1891 derived from another String.
1892 */
1893 tmp_value.mark_as_const();
1894 return (&tmp_value);
1895}
1896
1897/*
1898** The trim functions are extension to ANSI SQL because they trim substrings
1899** They ltrim() and rtrim() functions are optimized for 1 byte strings
1900** They also return the original string if possible, else they return
1901** a substring that points at the original string.
1902*/
1903
1904
1905String *Item_func_ltrim::val_str(String *str)
1906{
1907 DBUG_ASSERT(fixed == 1);
1908 char buff[MAX_FIELD_WIDTH], *ptr, *end;
1909 String tmp(buff,sizeof(buff),system_charset_info);
1910 String *res, *remove_str;
1911 uint UNINIT_VAR(remove_length);
1912
1913 res= args[0]->val_str(str);
1914 if ((null_value=args[0]->null_value))
1915 return 0;
1916 remove_str= &remove; /* Default value. */
1917 if (arg_count == 2)
1918 {
1919 remove_str= args[1]->val_str(&tmp);
1920 if ((null_value= args[1]->null_value))
1921 return 0;
1922 }
1923
1924 if ((remove_length= remove_str->length()) == 0 ||
1925 remove_length > res->length())
1926 return non_trimmed_value(res);
1927
1928 ptr= (char*) res->ptr();
1929 end= ptr+res->length();
1930 if (remove_length == 1)
1931 {
1932 char chr=(*remove_str)[0];
1933 while (ptr != end && *ptr == chr)
1934 ptr++;
1935 }
1936 else
1937 {
1938 const char *r_ptr=remove_str->ptr();
1939 end-=remove_length;
1940 while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
1941 ptr+=remove_length;
1942 end+=remove_length;
1943 }
1944 if (ptr == res->ptr())
1945 return non_trimmed_value(res);
1946 return trimmed_value(res, (uint32) (ptr - res->ptr()), (uint32) (end - ptr));
1947}
1948
1949
1950String *Item_func_rtrim::val_str(String *str)
1951{
1952 DBUG_ASSERT(fixed == 1);
1953 char buff[MAX_FIELD_WIDTH], *ptr, *end;
1954 String tmp(buff, sizeof(buff), system_charset_info);
1955 String *res, *remove_str;
1956 uint UNINIT_VAR(remove_length);
1957
1958 res= args[0]->val_str(str);
1959 if ((null_value=args[0]->null_value))
1960 return 0;
1961 remove_str= &remove; /* Default value. */
1962 if (arg_count == 2)
1963 {
1964 remove_str= args[1]->val_str(&tmp);
1965 if ((null_value= args[1]->null_value))
1966 return 0;
1967 }
1968
1969 if ((remove_length= remove_str->length()) == 0 ||
1970 remove_length > res->length())
1971 return non_trimmed_value(res);
1972
1973 ptr= (char*) res->ptr();
1974 end= ptr+res->length();
1975#ifdef USE_MB
1976 char *p=ptr;
1977 uint32 l;
1978#endif
1979 if (remove_length == 1)
1980 {
1981 char chr=(*remove_str)[0];
1982#ifdef USE_MB
1983 if (use_mb(collation.collation))
1984 {
1985 while (ptr < end)
1986 {
1987 if ((l= my_ismbchar(collation.collation, ptr, end))) ptr+= l, p=ptr;
1988 else ++ptr;
1989 }
1990 ptr=p;
1991 }
1992#endif
1993 while (ptr != end && end[-1] == chr)
1994 end--;
1995 }
1996 else
1997 {
1998 const char *r_ptr=remove_str->ptr();
1999#ifdef USE_MB
2000 if (use_mb(collation.collation))
2001 {
2002 loop:
2003 while (ptr + remove_length < end)
2004 {
2005 if ((l= my_ismbchar(collation.collation, ptr, end))) ptr+= l;
2006 else ++ptr;
2007 }
2008 if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
2009 {
2010 end-=remove_length;
2011 ptr=p;
2012 goto loop;
2013 }
2014 }
2015 else
2016#endif /* USE_MB */
2017 {
2018 while (ptr + remove_length <= end &&
2019 !memcmp(end-remove_length, r_ptr, remove_length))
2020 end-=remove_length;
2021 }
2022 }
2023 if (end == res->ptr()+res->length())
2024 return non_trimmed_value(res);
2025 return trimmed_value(res, 0, (uint32) (end - res->ptr()));
2026}
2027
2028
2029String *Item_func_trim::val_str(String *str)
2030{
2031 DBUG_ASSERT(fixed == 1);
2032 char buff[MAX_FIELD_WIDTH], *ptr, *end;
2033 const char *r_ptr;
2034 String tmp(buff, sizeof(buff), system_charset_info);
2035 String *res, *remove_str;
2036 uint UNINIT_VAR(remove_length);
2037
2038 res= args[0]->val_str(str);
2039 if ((null_value=args[0]->null_value))
2040 return 0;
2041 remove_str= &remove; /* Default value. */
2042 if (arg_count == 2)
2043 {
2044 remove_str= args[1]->val_str(&tmp);
2045 if ((null_value= args[1]->null_value))
2046 return 0;
2047 }
2048
2049 if ((remove_length= remove_str->length()) == 0 ||
2050 remove_length > res->length())
2051 return non_trimmed_value(res);
2052
2053 ptr= (char*) res->ptr();
2054 end= ptr+res->length();
2055 r_ptr= remove_str->ptr();
2056 while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
2057 ptr+=remove_length;
2058#ifdef USE_MB
2059 if (use_mb(collation.collation))
2060 {
2061 char *p=ptr;
2062 uint32 l;
2063 loop:
2064 while (ptr + remove_length < end)
2065 {
2066 if ((l= my_ismbchar(collation.collation, ptr, end)))
2067 ptr+= l;
2068 else
2069 ++ptr;
2070 }
2071 if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
2072 {
2073 end-=remove_length;
2074 ptr=p;
2075 goto loop;
2076 }
2077 ptr=p;
2078 }
2079 else
2080#endif /* USE_MB */
2081 {
2082 while (ptr + remove_length <= end &&
2083 !memcmp(end-remove_length,r_ptr,remove_length))
2084 end-=remove_length;
2085 }
2086 if (ptr == res->ptr() && end == ptr+res->length())
2087 return non_trimmed_value(res);
2088 return trimmed_value(res, (uint32) (ptr - res->ptr()), (uint32) (end - ptr));
2089}
2090
2091void Item_func_trim::fix_length_and_dec()
2092{
2093 if (arg_count == 1)
2094 {
2095 agg_arg_charsets_for_string_result(collation, args, 1);
2096 DBUG_ASSERT(collation.collation != NULL);
2097 remove.set_charset(collation.collation);
2098 remove.set_ascii(" ",1);
2099 }
2100 else
2101 {
2102 // Handle character set for args[1] and args[0].
2103 // Note that we pass args[1] as the first item, and args[0] as the second.
2104 if (agg_arg_charsets_for_string_result_with_comparison(collation,
2105 &args[1], 2, -1))
2106 return;
2107 }
2108 fix_char_length(args[0]->max_char_length());
2109}
2110
2111void Item_func_trim::print(String *str, enum_query_type query_type)
2112{
2113 if (arg_count == 1)
2114 {
2115 Item_func::print(str, query_type);
2116 return;
2117 }
2118 str->append(Item_func_trim::func_name());
2119 str->append(func_name_ext());
2120 str->append('(');
2121 str->append(mode_name());
2122 str->append(' ');
2123 args[1]->print(str, query_type);
2124 str->append(STRING_WITH_LEN(" from "));
2125 args[0]->print(str, query_type);
2126 str->append(')');
2127}
2128
2129
2130/* Item_func_password */
2131
2132bool Item_func_password::fix_fields(THD *thd, Item **ref)
2133{
2134 if (deflt)
2135 alg= (thd->variables.old_passwords ? OLD : NEW);
2136 return Item_str_ascii_func::fix_fields(thd, ref);
2137}
2138
2139String *Item_func_password::val_str_ascii(String *str)
2140{
2141 DBUG_ASSERT(fixed == 1);
2142 String *res= args[0]->val_str(str);
2143 switch (alg){
2144 case NEW:
2145 if (args[0]->null_value || res->length() == 0)
2146 return make_empty_result();
2147 my_make_scrambled_password(tmp_value, res->ptr(), res->length());
2148 str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, &my_charset_latin1);
2149 break;
2150 case OLD:
2151 if ((null_value=args[0]->null_value))
2152 return 0;
2153 if (res->length() == 0)
2154 return make_empty_result();
2155 my_make_scrambled_password_323(tmp_value, res->ptr(), res->length());
2156 str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, &my_charset_latin1);
2157 break;
2158 default:
2159 DBUG_ASSERT(0);
2160 }
2161 return str;
2162}
2163
2164char *Item_func_password::alloc(THD *thd, const char *password,
2165 size_t pass_len, enum PW_Alg al)
2166{
2167 char *buff= (char *) thd->alloc((al==NEW)?
2168 SCRAMBLED_PASSWORD_CHAR_LENGTH + 1:
2169 SCRAMBLED_PASSWORD_CHAR_LENGTH_323 + 1);
2170 if (!buff)
2171 return NULL;
2172
2173 switch (al) {
2174 case NEW:
2175 my_make_scrambled_password(buff, password, pass_len);
2176 break;
2177 case OLD:
2178 my_make_scrambled_password_323(buff, password, pass_len);
2179 break;
2180 default:
2181 DBUG_ASSERT(0);
2182 }
2183 return buff;
2184}
2185
2186
2187
2188#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
2189
2190String *Item_func_encrypt::val_str(String *str)
2191{
2192 DBUG_ASSERT(fixed == 1);
2193#ifdef HAVE_CRYPT
2194 String *res =args[0]->val_str(str);
2195 char salt[3],*salt_ptr;
2196 if ((null_value=args[0]->null_value))
2197 return 0;
2198 if (res->length() == 0)
2199 return make_empty_result();
2200 if (arg_count == 1)
2201 { // generate random salt
2202 time_t timestamp=current_thd->query_start();
2203 salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
2204 salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
2205 salt[2] = 0;
2206 salt_ptr=salt;
2207 }
2208 else
2209 { // obtain salt from the first two bytes
2210 String *salt_str=args[1]->val_str(&tmp_value);
2211 if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
2212 return 0;
2213 salt_ptr= salt_str->c_ptr_safe();
2214 }
2215 mysql_mutex_lock(&LOCK_crypt);
2216 char *tmp= crypt(res->c_ptr_safe(),salt_ptr);
2217 if (!tmp)
2218 {
2219 mysql_mutex_unlock(&LOCK_crypt);
2220 null_value= 1;
2221 return 0;
2222 }
2223 str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
2224 str->copy();
2225 mysql_mutex_unlock(&LOCK_crypt);
2226 return str;
2227#else
2228 null_value=1;
2229 return 0;
2230#endif /* HAVE_CRYPT */
2231}
2232
2233bool Item_func_encode::seed()
2234{
2235 char buf[80];
2236 ulong rand_nr[2];
2237 String *key, tmp(buf, sizeof(buf), system_charset_info);
2238
2239 if (!(key= args[1]->val_str(&tmp)))
2240 return TRUE;
2241
2242 hash_password(rand_nr, key->ptr(), key->length());
2243 sql_crypt.init(rand_nr);
2244
2245 return FALSE;
2246}
2247
2248void Item_func_encode::fix_length_and_dec()
2249{
2250 max_length=args[0]->max_length;
2251 maybe_null=args[0]->maybe_null || args[1]->maybe_null;
2252 collation.set(&my_charset_bin);
2253 /* Precompute the seed state if the item is constant. */
2254 seeded= args[1]->const_item() &&
2255 (args[1]->result_type() == STRING_RESULT) && !seed();
2256}
2257
2258String *Item_func_encode::val_str(String *str)
2259{
2260 String *res;
2261 DBUG_ASSERT(fixed == 1);
2262
2263 if (!(res=args[0]->val_str(str)))
2264 {
2265 null_value= 1;
2266 return NULL;
2267 }
2268
2269 if (!seeded && seed())
2270 {
2271 null_value= 1;
2272 return NULL;
2273 }
2274
2275 null_value= 0;
2276 res= copy_if_not_alloced(str, res, res->length());
2277 crypto_transform(res);
2278 sql_crypt.reinit();
2279
2280 return res;
2281}
2282
2283void Item_func_encode::crypto_transform(String *res)
2284{
2285 sql_crypt.encode((char*) res->ptr(),res->length());
2286 res->set_charset(&my_charset_bin);
2287}
2288
2289void Item_func_decode::crypto_transform(String *res)
2290{
2291 sql_crypt.decode((char*) res->ptr(),res->length());
2292}
2293
2294
2295String *Item_func_database::val_str(String *str)
2296{
2297 DBUG_ASSERT(fixed == 1);
2298 THD *thd= current_thd;
2299 if (thd->db.str == NULL)
2300 {
2301 null_value= 1;
2302 return 0;
2303 }
2304 else
2305 str->copy(thd->db.str, thd->db.length, system_charset_info);
2306 null_value= 0;
2307 return str;
2308}
2309
2310
2311String *Item_func_sqlerrm::val_str(String *str)
2312{
2313 DBUG_ASSERT(fixed);
2314 DBUG_ASSERT(!null_value);
2315 Diagnostics_area::Sql_condition_iterator it=
2316 current_thd->get_stmt_da()->sql_conditions();
2317 const Sql_condition *err;
2318 if ((err= it++))
2319 {
2320 str->copy(err->get_message_text(), err->get_message_octet_length(),
2321 system_charset_info);
2322 return str;
2323 }
2324 str->copy(STRING_WITH_LEN("normal, successful completition"),
2325 system_charset_info);
2326 return str;
2327}
2328
2329
2330/**
2331 @note USER() is replicated correctly if binlog_format=ROW or (as of
2332 BUG#28086) binlog_format=MIXED, but is incorrectly replicated to ''
2333 if binlog_format=STATEMENT.
2334*/
2335bool Item_func_user::init(const char *user, const char *host)
2336{
2337 DBUG_ASSERT(fixed == 1);
2338
2339 // For system threads (e.g. replication SQL thread) user may be empty
2340 if (user)
2341 {
2342 CHARSET_INFO *cs= str_value.charset();
2343 size_t res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
2344
2345 if (str_value.alloc((uint) res_length))
2346 {
2347 null_value=1;
2348 return TRUE;
2349 }
2350
2351 res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), (uint) res_length,
2352 "%s@%s", user, host);
2353 str_value.length((uint) res_length);
2354 str_value.mark_as_const();
2355 }
2356 return FALSE;
2357}
2358
2359
2360Item *Item_func_sysconst::safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
2361{
2362 /*
2363 During view or prepared statement creation, the item should not
2364 make use of const_charset_converter as it would imply substitution
2365 with constant items which is not correct. Functions can have different
2366 values during view creation and view execution based on context.
2367
2368 Return the identical item during view creation and prepare.
2369 */
2370 if (thd->lex->is_ps_or_view_context_analysis())
2371 return this;
2372 return const_charset_converter(thd, tocs, true, fully_qualified_func_name());
2373}
2374
2375bool Item_func_sysconst::const_item() const
2376{
2377 if (current_thd->lex->is_ps_or_view_context_analysis())
2378 return false;
2379 return true;
2380}
2381
2382bool Item_func_user::fix_fields(THD *thd, Item **ref)
2383{
2384 return (Item_func_sysconst::fix_fields(thd, ref) ||
2385 init(thd->main_security_ctx.user,
2386 thd->main_security_ctx.host_or_ip));
2387}
2388
2389
2390bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
2391{
2392 if (Item_func_sysconst::fix_fields(thd, ref))
2393 return TRUE;
2394
2395 Security_context *ctx= context && context->security_ctx
2396 ? context->security_ctx : thd->security_ctx;
2397 return init(ctx->priv_user, ctx->priv_host);
2398}
2399
2400bool Item_func_current_role::fix_fields(THD *thd, Item **ref)
2401{
2402 if (Item_func_sysconst::fix_fields(thd, ref))
2403 return 1;
2404
2405 Security_context *ctx= context && context->security_ctx
2406 ? context->security_ctx : thd->security_ctx;
2407 if (ctx->priv_role[0])
2408 {
2409 if (str_value.copy(ctx->priv_role, strlen(ctx->priv_role),
2410 system_charset_info))
2411 return 1;
2412 str_value.mark_as_const();
2413 null_value= maybe_null= 0;
2414 return 0;
2415 }
2416 null_value= maybe_null= 1;
2417 return 0;
2418}
2419
2420void Item_func_soundex::fix_length_and_dec()
2421{
2422 uint32 char_length= args[0]->max_char_length();
2423 agg_arg_charsets_for_string_result(collation, args, 1);
2424 DBUG_ASSERT(collation.collation != NULL);
2425 set_if_bigger(char_length, 4);
2426 fix_char_length(char_length);
2427}
2428
2429
2430/**
2431 If alpha, map input letter to soundex code.
2432 If not alpha and remove_garbage is set then skip to next char
2433 else return 0
2434*/
2435
2436static int soundex_toupper(int ch)
2437{
2438 return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch;
2439}
2440
2441
2442static char get_scode(int wc)
2443{
2444 int ch= soundex_toupper(wc);
2445 if (ch < 'A' || ch > 'Z')
2446 {
2447 // Thread extended alfa (country spec)
2448 return '0'; // as vokal
2449 }
2450 return(soundex_map[ch-'A']);
2451}
2452
2453
2454static bool my_uni_isalpha(int wc)
2455{
2456 /*
2457 Return true for all Basic Latin letters: a..z A..Z.
2458 Return true for all Unicode characters with code higher than U+00C0:
2459 - characters between 'z' and U+00C0 are controls and punctuations.
2460 - "U+00C0 LATIN CAPITAL LETTER A WITH GRAVE" is the first letter after 'z'.
2461 */
2462 return (wc >= 'a' && wc <= 'z') ||
2463 (wc >= 'A' && wc <= 'Z') ||
2464 (wc >= 0xC0);
2465}
2466
2467
2468String *Item_func_soundex::val_str(String *str)
2469{
2470 DBUG_ASSERT(fixed == 1);
2471 String *res= args[0]->val_str(&tmp_value);
2472 char last_ch,ch;
2473 CHARSET_INFO *cs= collation.collation;
2474 my_wc_t wc;
2475 uint nchars;
2476 int rc;
2477
2478 if ((null_value= args[0]->null_value))
2479 return 0; /* purecov: inspected */
2480
2481 if (str->alloc(MY_MAX(res->length(), 4 * cs->mbminlen)))
2482 return &tmp_value; /* purecov: inspected */
2483 str->set_charset(collation.collation);
2484 char *to= (char *) str->ptr();
2485 char *to_end= to + str->alloced_length();
2486 char *from= (char *) res->ptr(), *end= from + res->length();
2487
2488 for ( ; ; ) /* Skip pre-space */
2489 {
2490 if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2491 return make_empty_result(); /* EOL or invalid byte sequence */
2492
2493 if (rc == 1 && cs->ctype)
2494 {
2495 /* Single byte letter found */
2496 if (my_isalpha(cs, *from))
2497 {
2498 last_ch= get_scode(*from); // Code of the first letter
2499 *to++= soundex_toupper(*from++); // Copy first letter
2500 break;
2501 }
2502 from++;
2503 }
2504 else
2505 {
2506 from+= rc;
2507 if (my_uni_isalpha(wc))
2508 {
2509 /* Multibyte letter found */
2510 wc= soundex_toupper(wc);
2511 last_ch= get_scode(wc); // Code of the first letter
2512 if ((rc= cs->cset->wc_mb(cs, wc, (uchar*) to, (uchar*) to_end)) <= 0)
2513 {
2514 /* Extra safety - should not really happen */
2515 DBUG_ASSERT(false);
2516 return make_empty_result();
2517 }
2518 to+= rc;
2519 break;
2520 }
2521 }
2522 }
2523
2524 /*
2525 last_ch is now set to the first 'double-letter' check.
2526 loop on input letters until end of input
2527 */
2528 for (nchars= 1 ; ; )
2529 {
2530 if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2531 break; /* EOL or invalid byte sequence */
2532
2533 if (rc == 1 && cs->ctype)
2534 {
2535 if (!my_isalpha(cs, *from++))
2536 continue;
2537 }
2538 else
2539 {
2540 from+= rc;
2541 if (!my_uni_isalpha(wc))
2542 continue;
2543 }
2544
2545 ch= get_scode(wc);
2546 if ((ch != '0') && (ch != last_ch)) // if not skipped or double
2547 {
2548 // letter, copy to output
2549 if ((rc= cs->cset->wc_mb(cs, (my_wc_t) ch,
2550 (uchar*) to, (uchar*) to_end)) <= 0)
2551 {
2552 // Extra safety - should not really happen
2553 DBUG_ASSERT(false);
2554 break;
2555 }
2556 to+= rc;
2557 nchars++;
2558 last_ch= ch; // save code of last input letter
2559 } // for next double-letter check
2560 }
2561
2562 /* Pad up to 4 characters with DIGIT ZERO, if the string is shorter */
2563 if (nchars < 4)
2564 {
2565 uint nbytes= (4 - nchars) * cs->mbminlen;
2566 cs->cset->fill(cs, to, nbytes, '0');
2567 to+= nbytes;
2568 }
2569
2570 str->length((uint) (to - str->ptr()));
2571 return str;
2572}
2573
2574
2575/**
2576 Change a number to format '3,333,333,333.000'.
2577
2578 This should be 'internationalized' sometimes.
2579*/
2580
2581const int FORMAT_MAX_DECIMALS= 30;
2582
2583
2584void Item_func_format::fix_length_and_dec()
2585{
2586 uint32 char_length= args[0]->max_char_length();
2587 uint32 max_sep_count= (char_length / 3) + (decimals ? 1 : 0) + /*sign*/1;
2588 collation.set(default_charset());
2589 fix_char_length(char_length + max_sep_count + decimals);
2590 if (arg_count == 3)
2591 locale= args[2]->basic_const_item() ? args[2]->locale_from_val_str() : NULL;
2592 else
2593 locale= &my_locale_en_US; /* Two arguments */
2594}
2595
2596
2597/**
2598 @todo
2599 This needs to be fixed for multi-byte character set where numbers
2600 are stored in more than one byte
2601*/
2602
2603String *Item_func_format::val_str_ascii(String *str)
2604{
2605 uint32 str_length;
2606 /* Number of decimal digits */
2607 int dec;
2608 /* Number of characters used to represent the decimals, including '.' */
2609 uint32 dec_length;
2610 const MY_LOCALE *lc;
2611 DBUG_ASSERT(fixed == 1);
2612
2613 dec= (int) args[1]->val_int();
2614 if (args[1]->null_value)
2615 {
2616 null_value=1;
2617 return NULL;
2618 }
2619
2620 lc= locale ? locale : args[2]->locale_from_val_str();
2621
2622 dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
2623 dec_length= dec ? dec+1 : 0;
2624 null_value=0;
2625
2626 if (args[0]->result_type() == DECIMAL_RESULT ||
2627 args[0]->result_type() == INT_RESULT)
2628 {
2629 my_decimal dec_val, rnd_dec, *res;
2630 res= args[0]->val_decimal(&dec_val);
2631 if ((null_value=args[0]->null_value))
2632 return 0; /* purecov: inspected */
2633 my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
2634 my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
2635 str_length= str->length();
2636 }
2637 else
2638 {
2639 double nr= args[0]->val_real();
2640 if ((null_value=args[0]->null_value))
2641 return 0; /* purecov: inspected */
2642 nr= my_double_round(nr, (longlong) dec, FALSE, FALSE);
2643 str->set_real(nr, dec, &my_charset_numeric);
2644 if (!std::isfinite(nr))
2645 return str;
2646 str_length=str->length();
2647 }
2648 /* We need this test to handle 'nan' and short values */
2649 if (lc->grouping[0] > 0 &&
2650 str_length >= dec_length + 1 + lc->grouping[0])
2651 {
2652 /* We need space for ',' between each group of digits as well. */
2653 char buf[2 * FLOATING_POINT_BUFFER];
2654 int count;
2655 const char *grouping= lc->grouping;
2656 char sign_length= *str->ptr() == '-' ? 1 : 0;
2657 const char *src= str->ptr() + str_length - dec_length - 1;
2658 const char *src_begin= str->ptr() + sign_length;
2659 char *dst= buf + sizeof(buf);
2660
2661 /* Put the fractional part */
2662 if (dec)
2663 {
2664 dst-= (dec + 1);
2665 *dst= lc->decimal_point;
2666 memcpy(dst + 1, src + 2, dec);
2667 }
2668
2669 /* Put the integer part with grouping */
2670 for (count= *grouping; src >= src_begin; count--)
2671 {
2672 /*
2673 When *grouping==0x80 (which means "end of grouping")
2674 count will be initialized to -1 and
2675 we'll never get into this "if" anymore.
2676 */
2677 if (count == 0)
2678 {
2679 *--dst= lc->thousand_sep;
2680 if (grouping[1])
2681 grouping++;
2682 count= *grouping;
2683 }
2684 DBUG_ASSERT(dst > buf);
2685 *--dst= *src--;
2686 }
2687
2688 if (sign_length) /* Put '-' */
2689 *--dst= *str->ptr();
2690
2691 /* Put the rest of the integer part without grouping */
2692 str->copy(dst, buf + sizeof(buf) - dst, &my_charset_latin1);
2693 }
2694 else if (dec_length && lc->decimal_point != '.')
2695 {
2696 /*
2697 For short values without thousands (<1000)
2698 replace decimal point to localized value.
2699 */
2700 DBUG_ASSERT(dec_length <= str_length);
2701 ((char*) str->ptr())[str_length - dec_length]= lc->decimal_point;
2702 }
2703 return str;
2704}
2705
2706
2707void Item_func_elt::fix_length_and_dec()
2708{
2709 uint32 char_length= 0;
2710 decimals=0;
2711
2712 if (agg_arg_charsets_for_string_result(collation, args + 1, arg_count - 1))
2713 return;
2714
2715 for (uint i= 1 ; i < arg_count ; i++)
2716 {
2717 set_if_bigger(char_length, args[i]->max_char_length());
2718 set_if_bigger(decimals,args[i]->decimals);
2719 }
2720 fix_char_length(char_length);
2721 maybe_null=1; // NULL if wrong first arg
2722}
2723
2724
2725double Item_func_elt::val_real()
2726{
2727 DBUG_ASSERT(fixed == 1);
2728 uint tmp;
2729 null_value=1;
2730 if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2731 return 0.0;
2732 double result= args[tmp]->val_real();
2733 null_value= args[tmp]->null_value;
2734 return result;
2735}
2736
2737
2738longlong Item_func_elt::val_int()
2739{
2740 DBUG_ASSERT(fixed == 1);
2741 uint tmp;
2742 null_value=1;
2743 if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2744 return 0;
2745
2746 longlong result= args[tmp]->val_int();
2747 null_value= args[tmp]->null_value;
2748 return result;
2749}
2750
2751
2752String *Item_func_elt::val_str(String *str)
2753{
2754 DBUG_ASSERT(fixed == 1);
2755 uint tmp;
2756 null_value=1;
2757 if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2758 return NULL;
2759
2760 String *result= args[tmp]->val_str(str);
2761 if (result)
2762 result->set_charset(collation.collation);
2763 null_value= args[tmp]->null_value;
2764 return result;
2765}
2766
2767
2768void Item_func_make_set::fix_length_and_dec()
2769{
2770 uint32 char_length= arg_count - 2; /* Separators */
2771
2772 if (agg_arg_charsets_for_string_result(collation, args + 1, arg_count - 1))
2773 return;
2774
2775 for (uint i=1 ; i < arg_count ; i++)
2776 char_length+= args[i]->max_char_length();
2777 fix_char_length(char_length);
2778}
2779
2780
2781String *Item_func_make_set::val_str(String *str)
2782{
2783 DBUG_ASSERT(fixed == 1);
2784 ulonglong bits;
2785 bool first_found=0;
2786 Item **ptr=args+1;
2787 String *result= make_empty_result();
2788
2789 bits=args[0]->val_int();
2790 if ((null_value=args[0]->null_value))
2791 return NULL;
2792
2793 if (arg_count < 65)
2794 bits &= ((ulonglong) 1 << (arg_count-1))-1;
2795
2796 for (; bits; bits >>= 1, ptr++)
2797 {
2798 if (bits & 1)
2799 {
2800 String *res= (*ptr)->val_str(str);
2801 if (res) // Skip nulls
2802 {
2803 if (!first_found)
2804 { // First argument
2805 first_found=1;
2806 if (res != str)
2807 result=res; // Use original string
2808 else
2809 {
2810 if (tmp_str.copy(*res)) // Don't use 'str'
2811 return make_empty_result();
2812 result= &tmp_str;
2813 }
2814 }
2815 else
2816 {
2817 if (result != &tmp_str)
2818 { // Copy data to tmp_str
2819 if (tmp_str.alloc(result->length()+res->length()+1) ||
2820 tmp_str.copy(*result))
2821 return make_empty_result();
2822 result= &tmp_str;
2823 }
2824 if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
2825 return make_empty_result();
2826 }
2827 }
2828 }
2829 }
2830 return result;
2831}
2832
2833
2834void Item_func_char::print(String *str, enum_query_type query_type)
2835{
2836 str->append(Item_func_char::func_name());
2837 str->append('(');
2838 print_args(str, 0, query_type);
2839 if (collation.collation != &my_charset_bin)
2840 {
2841 str->append(STRING_WITH_LEN(" using "));
2842 str->append(collation.collation->csname);
2843 }
2844 str->append(')');
2845}
2846
2847
2848String *Item_func_char::val_str(String *str)
2849{
2850 DBUG_ASSERT(fixed == 1);
2851 str->length(0);
2852 str->set_charset(collation.collation);
2853 for (uint i=0 ; i < arg_count ; i++)
2854 {
2855 int32 num=(int32) args[i]->val_int();
2856 if (!args[i]->null_value)
2857 append_char(str, num);
2858 }
2859 str->realloc(str->length()); // Add end 0 (for Purify)
2860 return check_well_formed_result(str);
2861}
2862
2863
2864void Item_func_char::append_char(String *str, int32 num)
2865{
2866 char tmp[4];
2867 if (num & 0xFF000000L)
2868 {
2869 mi_int4store(tmp, num);
2870 str->append(tmp, 4, &my_charset_bin);
2871 }
2872 else if (num & 0xFF0000L)
2873 {
2874 mi_int3store(tmp, num);
2875 str->append(tmp, 3, &my_charset_bin);
2876 }
2877 else if (num & 0xFF00L)
2878 {
2879 mi_int2store(tmp, num);
2880 str->append(tmp, 2, &my_charset_bin);
2881 }
2882 else
2883 {
2884 tmp[0]= (char) num;
2885 str->append(tmp, 1, &my_charset_bin);
2886 }
2887}
2888
2889
2890String *Item_func_chr::val_str(String *str)
2891{
2892 DBUG_ASSERT(fixed == 1);
2893 str->length(0);
2894 str->set_charset(collation.collation);
2895 int32 num=(int32) args[0]->val_int();
2896 if (!args[0]->null_value)
2897 append_char(str, num);
2898 else
2899 {
2900 null_value= 1;
2901 return 0;
2902 }
2903 str->realloc(str->length()); // Add end 0 (for Purify)
2904 return check_well_formed_result(str);
2905}
2906
2907
2908inline String* alloc_buffer(String *res,String *str,String *tmp_value,
2909 ulong length)
2910{
2911 if (res->alloced_length() < length)
2912 {
2913 if (str->alloced_length() >= length)
2914 {
2915 (void) str->copy(*res);
2916 str->length(length);
2917 return str;
2918 }
2919 if (tmp_value->alloc(length))
2920 return 0;
2921 (void) tmp_value->copy(*res);
2922 tmp_value->length(length);
2923 return tmp_value;
2924 }
2925 res->length(length);
2926 return res;
2927}
2928
2929
2930void Item_func_repeat::fix_length_and_dec()
2931{
2932 agg_arg_charsets_for_string_result(collation, args, 1);
2933 DBUG_ASSERT(collation.collation != NULL);
2934 if (args[1]->const_item())
2935 {
2936 /* must be longlong to avoid truncation */
2937 longlong count= args[1]->val_int();
2938
2939 /* Assumes that the maximum length of a String is < INT_MAX32. */
2940 /* Set here so that rest of code sees out-of-bound value as such. */
2941 if (args[1]->null_value)
2942 count= 0;
2943 else if (count > INT_MAX32)
2944 count= INT_MAX32;
2945
2946 ulonglong char_length= (ulonglong) args[0]->max_char_length() * count;
2947 fix_char_length_ulonglong(char_length);
2948 }
2949 else
2950 {
2951 max_length= MAX_BLOB_WIDTH;
2952 maybe_null= 1;
2953 }
2954}
2955
2956/**
2957 Item_func_repeat::str is carefully written to avoid reallocs
2958 as much as possible at the cost of a local buffer
2959*/
2960
2961String *Item_func_repeat::val_str(String *str)
2962{
2963 DBUG_ASSERT(fixed == 1);
2964 uint length,tot_length;
2965 char *to;
2966 /* must be longlong to avoid truncation */
2967 longlong count= args[1]->val_int();
2968 String *res= args[0]->val_str(str);
2969
2970 if (args[0]->null_value || args[1]->null_value)
2971 goto err; // string and/or delim are null
2972 null_value= 0;
2973
2974 if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
2975 return make_empty_result();
2976
2977 /* Assumes that the maximum length of a String is < INT_MAX32. */
2978 /* Bounds check on count: If this is triggered, we will error. */
2979 if ((ulonglong) count > INT_MAX32)
2980 count= INT_MAX32;
2981 if (count == 1) // To avoid reallocs
2982 return res;
2983 length=res->length();
2984
2985 // Safe length check
2986 {
2987 THD *thd= current_thd;
2988 if (length > thd->variables.max_allowed_packet / (uint) count)
2989 {
2990 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
2991 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2992 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2993 func_name(), thd->variables.max_allowed_packet);
2994 goto err;
2995 }
2996 }
2997 tot_length= length*(uint) count;
2998 if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
2999 goto err;
3000
3001 to=(char*) res->ptr()+length;
3002 while (--count)
3003 {
3004 memcpy(to,res->ptr(),length);
3005 to+=length;
3006 }
3007 return (res);
3008
3009err:
3010 null_value=1;
3011 return 0;
3012}
3013
3014
3015void Item_func_space::fix_length_and_dec()
3016{
3017 collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
3018 if (args[0]->const_item())
3019 {
3020 /* must be longlong to avoid truncation */
3021 longlong count= args[0]->val_int();
3022 if (args[0]->null_value)
3023 goto end;
3024 /*
3025 Assumes that the maximum length of a String is < INT_MAX32.
3026 Set here so that rest of code sees out-of-bound value as such.
3027 */
3028 if (count > INT_MAX32)
3029 count= INT_MAX32;
3030 fix_char_length_ulonglong(count);
3031 return;
3032 }
3033
3034end:
3035 max_length= MAX_BLOB_WIDTH;
3036 maybe_null= 1;
3037}
3038
3039
3040String *Item_func_space::val_str(String *str)
3041{
3042 uint tot_length;
3043 longlong count= args[0]->val_int();
3044 CHARSET_INFO *cs= collation.collation;
3045
3046 if (args[0]->null_value)
3047 goto err; // string and/or delim are null
3048 null_value= 0;
3049
3050 if (count <= 0 && (count == 0 || !args[0]->unsigned_flag))
3051 return make_empty_result();
3052 /*
3053 Assumes that the maximum length of a String is < INT_MAX32.
3054 Bounds check on count: If this is triggered, we will error.
3055 */
3056 if ((ulonglong) count > INT_MAX32)
3057 count= INT_MAX32;
3058
3059 // Safe length check
3060 tot_length= (uint) count * cs->mbminlen;
3061 {
3062 THD *thd= current_thd;
3063 if (tot_length > thd->variables.max_allowed_packet)
3064 {
3065 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3066 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3067 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3068 func_name(),
3069 thd->variables.max_allowed_packet);
3070 goto err;
3071 }
3072 }
3073 if (str->alloc(tot_length))
3074 goto err;
3075 str->length(tot_length);
3076 str->set_charset(cs);
3077 cs->cset->fill(cs, (char*) str->ptr(), tot_length, ' ');
3078 return str;
3079
3080err:
3081 null_value= 1;
3082 return 0;
3083}
3084
3085
3086void Item_func_binlog_gtid_pos::fix_length_and_dec()
3087{
3088 collation.set(system_charset_info);
3089 max_length= MAX_BLOB_WIDTH;
3090 maybe_null= 1;
3091}
3092
3093
3094String *Item_func_binlog_gtid_pos::val_str(String *str)
3095{
3096 DBUG_ASSERT(fixed == 1);
3097#ifndef HAVE_REPLICATION
3098 null_value= 0;
3099 str->copy("", 0, system_charset_info);
3100 return str;
3101#else
3102 String name_str, *name;
3103 longlong pos;
3104
3105 if (args[0]->null_value || args[1]->null_value)
3106 goto err;
3107
3108 name= args[0]->val_str(&name_str);
3109 pos= args[1]->val_int();
3110
3111 if (pos < 0 || pos > UINT_MAX32)
3112 goto err;
3113
3114 if (gtid_state_from_binlog_pos(name->c_ptr_safe(), (uint32)pos, str))
3115 goto err;
3116 null_value= 0;
3117 return str;
3118
3119err:
3120 null_value= 1;
3121 return NULL;
3122#endif /* !HAVE_REPLICATION */
3123}
3124
3125
3126void Item_func_pad::fix_length_and_dec()
3127{
3128 if (arg_count == 3)
3129 {
3130 // Handle character set for args[0] and args[2].
3131 if (agg_arg_charsets_for_string_result(collation, &args[0], 2, 2))
3132 return;
3133 }
3134 else
3135 {
3136 if (agg_arg_charsets_for_string_result(collation, &args[0], 1, 1))
3137 return;
3138 pad_str.set_charset(collation.collation);
3139 pad_str.length(0);
3140 pad_str.append(" ", 1);
3141 }
3142
3143 if (args[1]->const_item())
3144 {
3145 ulonglong char_length= (ulonglong) args[1]->val_int();
3146 DBUG_ASSERT(collation.collation->mbmaxlen > 0);
3147 /* Assumes that the maximum length of a String is < INT_MAX32. */
3148 /* Set here so that rest of code sees out-of-bound value as such. */
3149 if (args[1]->null_value)
3150 char_length= 0;
3151 else if (char_length > INT_MAX32)
3152 char_length= INT_MAX32;
3153 fix_char_length_ulonglong(char_length);
3154 }
3155 else
3156 {
3157 max_length= MAX_BLOB_WIDTH;
3158 maybe_null= 1;
3159 }
3160}
3161
3162
3163String *Item_func_rpad::val_str(String *str)
3164{
3165 DBUG_ASSERT(fixed == 1);
3166 uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
3167 char *to;
3168 const char *ptr_pad;
3169 /* must be longlong to avoid truncation */
3170 longlong count= args[1]->val_int();
3171 longlong byte_count;
3172 String *res= args[0]->val_str(str);
3173 String *rpad= arg_count == 2 ? &pad_str : args[2]->val_str(&pad_str);
3174
3175 if (!res || args[1]->null_value || !rpad ||
3176 ((count < 0) && !args[1]->unsigned_flag))
3177 goto err;
3178
3179 null_value=0;
3180
3181 if (count == 0)
3182 return make_empty_result();
3183
3184 /* Assumes that the maximum length of a String is < INT_MAX32. */
3185 /* Set here so that rest of code sees out-of-bound value as such. */
3186 if ((ulonglong) count > INT_MAX32)
3187 count= INT_MAX32;
3188 /*
3189 There is one exception not handled (intentionaly) by the character set
3190 aggregation code. If one string is strong side and is binary, and
3191 another one is weak side and is a multi-byte character string,
3192 then we need to operate on the second string in terms on bytes when
3193 calling ::numchars() and ::charpos(), rather than in terms of characters.
3194 Lets substitute its character set to binary.
3195 */
3196 if (collation.collation == &my_charset_bin)
3197 {
3198 res->set_charset(&my_charset_bin);
3199 rpad->set_charset(&my_charset_bin);
3200 }
3201
3202 if (count <= (res_char_length= res->numchars()))
3203 { // String to pad is big enough
3204 res->length(res->charpos((int) count)); // Shorten result if longer
3205 return (res);
3206 }
3207
3208 byte_count= count * collation.collation->mbmaxlen;
3209 {
3210 THD *thd= current_thd;
3211 if ((ulonglong) byte_count > thd->variables.max_allowed_packet)
3212 {
3213 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3214 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3215 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3216 func_name(), thd->variables.max_allowed_packet);
3217 goto err;
3218 }
3219 }
3220
3221 if (arg_count == 3)
3222 {
3223 if (args[2]->null_value || !(pad_char_length= rpad->numchars()))
3224 goto err;
3225 }
3226 else
3227 pad_char_length= 1; // Implicit space
3228
3229 res_byte_length= res->length(); /* Must be done before alloc_buffer */
3230 if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
3231 goto err;
3232
3233 to= (char*) res->ptr()+res_byte_length;
3234 ptr_pad=rpad->ptr();
3235 pad_byte_length= rpad->length();
3236 count-= res_char_length;
3237 for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
3238 {
3239 memcpy(to,ptr_pad,pad_byte_length);
3240 to+= pad_byte_length;
3241 }
3242 if (count)
3243 {
3244 pad_byte_length= rpad->charpos((int) count);
3245 memcpy(to,ptr_pad,(size_t) pad_byte_length);
3246 to+= pad_byte_length;
3247 }
3248 res->length((uint) (to- (char*) res->ptr()));
3249 return (res);
3250
3251 err:
3252 null_value=1;
3253 return 0;
3254}
3255
3256
3257String *Item_func_lpad::val_str(String *str)
3258{
3259 DBUG_ASSERT(fixed == 1);
3260 uint32 res_char_length,pad_char_length;
3261 /* must be longlong to avoid truncation */
3262 longlong count= args[1]->val_int();
3263 longlong byte_count;
3264 String *res= args[0]->val_str(&tmp_value);
3265 String *pad= arg_count == 2 ? &pad_str : args[2]->val_str(&pad_str);
3266
3267 if (!res || args[1]->null_value || !pad ||
3268 ((count < 0) && !args[1]->unsigned_flag))
3269 goto err;
3270
3271 null_value=0;
3272
3273 if (count == 0)
3274 return make_empty_result();
3275
3276 /* Assumes that the maximum length of a String is < INT_MAX32. */
3277 /* Set here so that rest of code sees out-of-bound value as such. */
3278 if ((ulonglong) count > INT_MAX32)
3279 count= INT_MAX32;
3280
3281 /*
3282 There is one exception not handled (intentionaly) by the character set
3283 aggregation code. If one string is strong side and is binary, and
3284 another one is weak side and is a multi-byte character string,
3285 then we need to operate on the second string in terms on bytes when
3286 calling ::numchars() and ::charpos(), rather than in terms of characters.
3287 Lets substitute its character set to binary.
3288 */
3289 if (collation.collation == &my_charset_bin)
3290 {
3291 res->set_charset(&my_charset_bin);
3292 pad->set_charset(&my_charset_bin);
3293 }
3294
3295 res_char_length= res->numchars();
3296
3297 if (count <= res_char_length)
3298 {
3299 res->length(res->charpos((int) count));
3300 return res;
3301 }
3302
3303 byte_count= count * collation.collation->mbmaxlen;
3304
3305 {
3306 THD *thd= current_thd;
3307 if ((ulonglong) byte_count > thd->variables.max_allowed_packet)
3308 {
3309 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3310 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3311 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3312 func_name(), thd->variables.max_allowed_packet);
3313 goto err;
3314 }
3315 }
3316
3317 if (str->alloc((uint32) byte_count))
3318 goto err;
3319
3320 if (arg_count == 3)
3321 {
3322 if (args[2]->null_value || !(pad_char_length= pad->numchars()))
3323 goto err;
3324 }
3325 else
3326 pad_char_length= 1; // Implicit space
3327
3328 str->length(0);
3329 str->set_charset(collation.collation);
3330 count-= res_char_length;
3331 while (count >= pad_char_length)
3332 {
3333 str->append(*pad);
3334 count-= pad_char_length;
3335 }
3336 if (count > 0)
3337 str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
3338
3339 str->append(*res);
3340 null_value= 0;
3341 return str;
3342
3343err:
3344 null_value= 1;
3345 return 0;
3346}
3347
3348
3349String *Item_func_conv::val_str(String *str)
3350{
3351 DBUG_ASSERT(fixed == 1);
3352 String *res= args[0]->val_str(str);
3353 char *endptr,ans[65],*ptr;
3354 longlong dec;
3355 int from_base= (int) args[1]->val_int();
3356 int to_base= (int) args[2]->val_int();
3357 int err;
3358
3359 // Note that abs(INT_MIN) is undefined.
3360 if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
3361 from_base == INT_MIN || to_base == INT_MIN ||
3362 abs(to_base) > 36 || abs(to_base) < 2 ||
3363 abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
3364 {
3365 null_value= 1;
3366 return NULL;
3367 }
3368 null_value= 0;
3369 unsigned_flag= !(from_base < 0);
3370
3371 if (args[0]->field_type() == MYSQL_TYPE_BIT)
3372 {
3373 /*
3374 Special case: The string representation of BIT doesn't resemble the
3375 decimal representation, so we shouldn't change it to string and then to
3376 decimal.
3377 */
3378 dec= args[0]->val_int();
3379 }
3380 else
3381 {
3382 if (from_base < 0)
3383 dec= my_strntoll(res->charset(), res->ptr(), res->length(),
3384 -from_base, &endptr, &err);
3385 else
3386 dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
3387 from_base, &endptr, &err);
3388 }
3389
3390 if (!(ptr= longlong2str(dec, ans, to_base)) ||
3391 str->copy(ans, (uint32) (ptr - ans), default_charset()))
3392 {
3393 null_value= 1;
3394 return NULL;
3395 }
3396 return str;
3397}
3398
3399
3400String *Item_func_conv_charset::val_str(String *str)
3401{
3402 DBUG_ASSERT(fixed == 1);
3403 if (use_cached_value)
3404 return null_value ? 0 : &str_value;
3405 String *arg= args[0]->val_str(&tmp_value);
3406 String_copier_for_item copier(current_thd);
3407 return ((null_value= args[0]->null_value ||
3408 copier.copy_with_warn(collation.collation, str,
3409 arg->charset(), arg->ptr(),
3410 arg->length(), arg->length()))) ?
3411 0 : str;
3412}
3413
3414void Item_func_conv_charset::fix_length_and_dec()
3415{
3416 DBUG_ASSERT(collation.derivation == DERIVATION_IMPLICIT);
3417 fix_char_length(args[0]->max_char_length());
3418}
3419
3420void Item_func_conv_charset::print(String *str, enum_query_type query_type)
3421{
3422 str->append(STRING_WITH_LEN("convert("));
3423 args[0]->print(str, query_type);
3424 str->append(STRING_WITH_LEN(" using "));
3425 str->append(collation.collation->csname);
3426 str->append(')');
3427}
3428
3429String *Item_func_set_collation::val_str(String *str)
3430{
3431 DBUG_ASSERT(fixed == 1);
3432 str=args[0]->val_str(str);
3433 if ((null_value=args[0]->null_value))
3434 return 0;
3435 str->set_charset(collation.collation);
3436 return str;
3437}
3438
3439void Item_func_set_collation::fix_length_and_dec()
3440{
3441 if (!my_charset_same(args[0]->collation.collation, m_set_collation))
3442 {
3443 my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
3444 m_set_collation->name, args[0]->collation.collation->csname);
3445 return;
3446 }
3447 collation.set(m_set_collation, DERIVATION_EXPLICIT,
3448 args[0]->collation.repertoire);
3449 max_length= args[0]->max_length;
3450}
3451
3452
3453bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
3454{
3455 return Item_func::eq(item, binary_cmp) &&
3456 collation.collation == item->collation.collation;
3457}
3458
3459
3460void Item_func_set_collation::print(String *str, enum_query_type query_type)
3461{
3462 args[0]->print_parenthesised(str, query_type, precedence());
3463 str->append(STRING_WITH_LEN(" collate "));
3464 str->append(m_set_collation->name);
3465}
3466
3467String *Item_func_charset::val_str(String *str)
3468{
3469 DBUG_ASSERT(fixed == 1);
3470 uint dummy_errors;
3471
3472 CHARSET_INFO *cs= args[0]->charset_for_protocol();
3473 null_value= 0;
3474 str->copy(cs->csname, (uint) strlen(cs->csname),
3475 &my_charset_latin1, collation.collation, &dummy_errors);
3476 return str;
3477}
3478
3479String *Item_func_collation::val_str(String *str)
3480{
3481 DBUG_ASSERT(fixed == 1);
3482 uint dummy_errors;
3483 CHARSET_INFO *cs= args[0]->charset_for_protocol();
3484
3485 null_value= 0;
3486 str->copy(cs->name, (uint) strlen(cs->name),
3487 &my_charset_latin1, collation.collation, &dummy_errors);
3488 return str;
3489}
3490
3491
3492void Item_func_weight_string::fix_length_and_dec()
3493{
3494 CHARSET_INFO *cs= args[0]->collation.collation;
3495 collation.set(&my_charset_bin, args[0]->collation.derivation);
3496 flags= my_strxfrm_flag_normalize(flags, cs->levels_for_order);
3497 /*
3498 Use result_length if it was given explicitly in constructor,
3499 otherwise calculate max_length using argument's max_length
3500 and "nweights".
3501 */
3502 if (!(max_length= result_length))
3503 {
3504 size_t char_length;
3505 char_length= ((cs->state & MY_CS_STRNXFRM_BAD_NWEIGHTS) || !nweights) ?
3506 args[0]->max_char_length() : nweights * cs->levels_for_order;
3507 max_length= (uint32)cs->coll->strnxfrmlen(cs, char_length * cs->mbmaxlen);
3508 }
3509 maybe_null= 1;
3510}
3511
3512
3513/* Return a weight_string according to collation */
3514String *Item_func_weight_string::val_str(String *str)
3515{
3516 String *res;
3517 CHARSET_INFO *cs= args[0]->collation.collation;
3518 size_t tmp_length, frm_length;
3519 DBUG_ASSERT(fixed == 1);
3520
3521 if (args[0]->result_type() != STRING_RESULT ||
3522 !(res= args[0]->val_str(&tmp_value)))
3523 goto nl;
3524
3525 /*
3526 Use result_length if it was given in constructor
3527 explicitly, otherwise calculate result length
3528 from argument and "nweights".
3529 */
3530 if (!(tmp_length= result_length))
3531 {
3532 size_t char_length;
3533 if (cs->state & MY_CS_STRNXFRM_BAD_NWEIGHTS)
3534 {
3535 /*
3536 latin2_czech_cs and cp1250_czech_cs do not support
3537 the "nweights" limit in strnxfrm(). Use the full length.
3538 */
3539 char_length= res->length();
3540 }
3541 else
3542 {
3543 /*
3544 If we don't need to pad the result with spaces, then it should be
3545 OK to calculate character length of the argument approximately:
3546 "res->length() / cs->mbminlen" can return a number that is
3547 bigger than the real number of characters in the string, so
3548 we'll allocate a little bit more memory but avoid calling
3549 the slow res->numchars().
3550 In case if we do need to pad with spaces, we call res->numchars()
3551 to know the true number of characters.
3552 */
3553 if (!(char_length= nweights))
3554 char_length= (flags & MY_STRXFRM_PAD_WITH_SPACE) ?
3555 res->numchars() : (res->length() / cs->mbminlen);
3556 }
3557 tmp_length= cs->coll->strnxfrmlen(cs, char_length * cs->mbmaxlen);
3558 }
3559
3560 {
3561 THD *thd= current_thd;
3562 if (tmp_length > current_thd->variables.max_allowed_packet)
3563 {
3564 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3565 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3566 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3567 func_name(),
3568 thd->variables.max_allowed_packet);
3569 goto nl;
3570 }
3571 }
3572
3573 if (str->alloc(tmp_length))
3574 goto nl;
3575
3576 frm_length= cs->coll->strnxfrm(cs,
3577 (uchar *) str->ptr(), tmp_length,
3578 nweights ? nweights : (uint)tmp_length,
3579 (const uchar *) res->ptr(), res->length(),
3580 flags);
3581 DBUG_ASSERT(frm_length <= tmp_length);
3582
3583 str->length(frm_length);
3584 null_value= 0;
3585 return str;
3586
3587nl:
3588 null_value= 1;
3589 return 0;
3590}
3591
3592
3593void Item_func_weight_string::print(String *str, enum_query_type query_type)
3594{
3595 str->append(func_name());
3596 str->append('(');
3597 args[0]->print(str, query_type);
3598 str->append(',');
3599 str->append_ulonglong(result_length);
3600 str->append(',');
3601 str->append_ulonglong(nweights);
3602 str->append(',');
3603 str->append_ulonglong(flags);
3604 str->append(')');
3605}
3606
3607
3608String *Item_func_hex::val_str_ascii_from_val_real(String *str)
3609{
3610 ulonglong dec;
3611 double val= args[0]->val_real();
3612 if ((null_value= args[0]->null_value))
3613 return 0;
3614 if ((val <= (double) LONGLONG_MIN) ||
3615 (val >= (double) (ulonglong) ULONGLONG_MAX))
3616 dec= ~(longlong) 0;
3617 else
3618 dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
3619 return str->set_hex(dec) ? make_empty_result() : str;
3620}
3621
3622
3623String *Item_func_hex::val_str_ascii_from_val_str(String *str)
3624{
3625 DBUG_ASSERT(&tmp_value != str);
3626 String *res= args[0]->val_str(&tmp_value);
3627 DBUG_ASSERT(res != str);
3628 if ((null_value= (res == NULL)))
3629 return NULL;
3630 return str->set_hex(res->ptr(), res->length()) ? make_empty_result() : str;
3631}
3632
3633
3634String *Item_func_hex::val_str_ascii_from_val_int(String *str)
3635{
3636 ulonglong dec= (ulonglong) args[0]->val_int();
3637 if ((null_value= args[0]->null_value))
3638 return 0;
3639 return str->set_hex(dec) ? make_empty_result() : str;
3640}
3641
3642
3643 /** Convert given hex string to a binary string. */
3644
3645String *Item_func_unhex::val_str(String *str)
3646{
3647 const char *from, *end;
3648 char *to;
3649 String *res;
3650 uint length;
3651 DBUG_ASSERT(fixed == 1);
3652
3653 res= args[0]->val_str(&tmp_value);
3654 if (!res || str->alloc(length= (1+res->length())/2))
3655 {
3656 null_value=1;
3657 return 0;
3658 }
3659
3660 from= res->ptr();
3661 null_value= 0;
3662 str->length(length);
3663 to= (char*) str->ptr();
3664 if (res->length() % 2)
3665 {
3666 int hex_char;
3667 *to++= hex_char= hexchar_to_int(*from++);
3668 if ((null_value= (hex_char == -1)))
3669 return 0;
3670 }
3671 for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
3672 {
3673 int hex_char;
3674 *to= (hex_char= hexchar_to_int(from[0])) << 4;
3675 if ((null_value= (hex_char == -1)))
3676 return 0;
3677 *to|= hex_char= hexchar_to_int(from[1]);
3678 if ((null_value= (hex_char == -1)))
3679 return 0;
3680 }
3681 return str;
3682}
3683
3684
3685#ifndef DBUG_OFF
3686String *Item_func_like_range::val_str(String *str)
3687{
3688 DBUG_ASSERT(fixed == 1);
3689 longlong nbytes= args[1]->val_int();
3690 String *res= args[0]->val_str(str);
3691 size_t min_len, max_len;
3692 CHARSET_INFO *cs= collation.collation;
3693
3694 if (!res || args[0]->null_value || args[1]->null_value ||
3695 nbytes < 0 || nbytes > MAX_BLOB_WIDTH ||
3696 min_str.alloc((size_t)nbytes) || max_str.alloc((size_t)nbytes))
3697 goto err;
3698 null_value=0;
3699
3700 if (cs->coll->like_range(cs, res->ptr(), res->length(),
3701 '\\', '_', '%', (size_t)nbytes,
3702 (char*) min_str.ptr(), (char*) max_str.ptr(),
3703 &min_len, &max_len))
3704 goto err;
3705
3706 min_str.set_charset(collation.collation);
3707 max_str.set_charset(collation.collation);
3708 min_str.length(min_len);
3709 max_str.length(max_len);
3710
3711 return is_min ? &min_str : &max_str;
3712
3713err:
3714 null_value= 1;
3715 return 0;
3716}
3717#endif
3718
3719
3720void Item_func_binary::print(String *str, enum_query_type query_type)
3721{
3722 str->append(STRING_WITH_LEN("cast("));
3723 args[0]->print(str, query_type);
3724 str->append(STRING_WITH_LEN(" as binary)"));
3725}
3726
3727
3728#include <my_dir.h> // For my_stat
3729
3730String *Item_load_file::val_str(String *str)
3731{
3732 DBUG_ASSERT(fixed == 1);
3733 String *file_name;
3734 File file;
3735 MY_STAT stat_info;
3736 char path[FN_REFLEN];
3737 DBUG_ENTER("load_file");
3738
3739 if (!(file_name= args[0]->val_str(str))
3740#ifndef NO_EMBEDDED_ACCESS_CHECKS
3741 || !(current_thd->security_ctx->master_access & FILE_ACL)
3742#endif
3743 )
3744 goto err;
3745
3746 (void) fn_format(path, file_name->c_ptr_safe(), mysql_real_data_home, "",
3747 MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
3748
3749 /* Read only allowed from within dir specified by secure_file_priv */
3750 if (!is_secure_file_path(path))
3751 goto err;
3752
3753 if (!mysql_file_stat(key_file_loadfile, path, &stat_info, MYF(0)))
3754 goto err;
3755
3756 if (!(stat_info.st_mode & S_IROTH))
3757 {
3758 /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
3759 goto err;
3760 }
3761
3762 {
3763 THD *thd= current_thd;
3764 if (stat_info.st_size > (long) thd->variables.max_allowed_packet)
3765 {
3766 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3767 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3768 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3769 func_name(), thd->variables.max_allowed_packet);
3770 goto err;
3771 }
3772 }
3773 if (tmp_value.alloc((size_t)stat_info.st_size))
3774 goto err;
3775 if ((file= mysql_file_open(key_file_loadfile,
3776 file_name->ptr(), O_RDONLY, MYF(0))) < 0)
3777 goto err;
3778 if (mysql_file_read(file, (uchar*) tmp_value.ptr(), (size_t)stat_info.st_size,
3779 MYF(MY_NABP)))
3780 {
3781 mysql_file_close(file, MYF(0));
3782 goto err;
3783 }
3784 tmp_value.length((uint32)stat_info.st_size);
3785 mysql_file_close(file, MYF(0));
3786 null_value = 0;
3787 DBUG_RETURN(&tmp_value);
3788
3789err:
3790 null_value = 1;
3791 DBUG_RETURN(0);
3792}
3793
3794
3795String* Item_func_export_set::val_str(String* str)
3796{
3797 DBUG_ASSERT(fixed == 1);
3798 String yes_buf, no_buf, sep_buf;
3799 const ulonglong the_set = (ulonglong) args[0]->val_int();
3800 const String *yes= args[1]->val_str(&yes_buf);
3801 const String *no= args[2]->val_str(&no_buf);
3802 const String *sep= NULL;
3803
3804 uint num_set_values = 64;
3805 str->length(0);
3806 str->set_charset(collation.collation);
3807
3808 /* Check if some argument is a NULL value */
3809 if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
3810 {
3811 null_value= true;
3812 return NULL;
3813 }
3814 /*
3815 Arg count can only be 3, 4 or 5 here. This is guaranteed from the
3816 grammar for EXPORT_SET()
3817 */
3818 switch(arg_count) {
3819 case 5:
3820 num_set_values = (uint) args[4]->val_int();
3821 if (num_set_values > 64)
3822 num_set_values=64;
3823 if (args[4]->null_value)
3824 {
3825 null_value= true;
3826 return NULL;
3827 }
3828 /* Fall through */
3829 case 4:
3830 if (!(sep = args[3]->val_str(&sep_buf))) // Only true if NULL
3831 {
3832 null_value= true;
3833 return NULL;
3834 }
3835 break;
3836 case 3:
3837 {
3838 /* errors is not checked - assume "," can always be converted */
3839 uint errors;
3840 sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin,
3841 collation.collation, &errors);
3842 sep = &sep_buf;
3843 }
3844 break;
3845 default:
3846 DBUG_ASSERT(0); // cannot happen
3847 }
3848 null_value= false;
3849
3850 THD *thd= current_thd;
3851 const ulong max_allowed_packet= thd->variables.max_allowed_packet;
3852 const uint num_separators= num_set_values > 0 ? num_set_values - 1 : 0;
3853 const ulonglong max_total_length=
3854 num_set_values * MY_MAX(yes->length(), no->length()) +
3855 num_separators * sep->length();
3856
3857 if (unlikely(max_total_length > max_allowed_packet))
3858 {
3859 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3860 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3861 ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3862 func_name(), max_allowed_packet);
3863 null_value= true;
3864 return NULL;
3865 }
3866
3867 uint ix;
3868 ulonglong mask;
3869 for (ix= 0, mask=0x1; ix < num_set_values; ++ix, mask = (mask << 1))
3870 {
3871 if (the_set & mask)
3872 str->append(*yes);
3873 else
3874 str->append(*no);
3875 if (ix != num_separators)
3876 str->append(*sep);
3877 }
3878 return str;
3879}
3880
3881void Item_func_export_set::fix_length_and_dec()
3882{
3883 uint32 length= MY_MAX(args[1]->max_char_length(), args[2]->max_char_length());
3884 uint32 sep_length= (arg_count > 3 ? args[3]->max_char_length() : 1);
3885
3886 if (agg_arg_charsets_for_string_result(collation,
3887 args + 1, MY_MIN(4, arg_count) - 1))
3888 return;
3889 fix_char_length(length * 64 + sep_length * 63);
3890}
3891
3892
3893#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))
3894
3895/**
3896 QUOTE() function returns argument string in single quotes suitable for
3897 using in a SQL statement.
3898
3899 Adds a \\ before all characters that needs to be escaped in a SQL string.
3900 We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
3901 running commands from a file in windows.
3902
3903 This function is very useful when you want to generate SQL statements.
3904
3905 @note
3906 QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).
3907
3908 @retval
3909 str Quoted string
3910 @retval
3911 NULL Out of memory.
3912*/
3913
3914String *Item_func_quote::val_str(String *str)
3915{
3916 DBUG_ASSERT(fixed == 1);
3917 /*
3918 Bit mask that has 1 for set for the position of the following characters:
3919 0, \, ' and ^Z
3920 */
3921
3922 static uchar escmask[32]=
3923 {
3924 0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
3925 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
3926 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3927 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
3928 };
3929
3930 ulong max_allowed_packet= current_thd->variables.max_allowed_packet;
3931 char *from, *to, *end, *start;
3932 String *arg= args[0]->val_str(&tmp_value);
3933 uint arg_length, new_length;
3934 if (!arg) // Null argument
3935 {
3936 /* Return the string 'NULL' */
3937 str->copy(STRING_WITH_LEN("NULL"), collation.collation);
3938 null_value= 0;
3939 return str;
3940 }
3941
3942 arg_length= arg->length();
3943
3944 if (collation.collation->mbmaxlen == 1)
3945 {
3946 new_length= arg_length + 2; /* for beginning and ending ' signs */
3947 for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
3948 new_length+= get_esc_bit(escmask, (uchar) *from);
3949 if (new_length > max_allowed_packet)
3950 goto toolong;
3951 }
3952 else
3953 {
3954 new_length= (arg_length * 2) + /* For string characters */
3955 (2 * collation.collation->mbmaxlen); /* For quotes */
3956 set_if_smaller(new_length, max_allowed_packet);
3957 }
3958
3959 if (str->alloc(new_length))
3960 goto null;
3961
3962 if (collation.collation->mbmaxlen > 1)
3963 {
3964 CHARSET_INFO *cs= collation.collation;
3965 int mblen;
3966 uchar *to_end;
3967 to= (char*) str->ptr();
3968 to_end= (uchar*) to + new_length;
3969
3970 /* Put leading quote */
3971 if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
3972 goto toolong;
3973 to+= mblen;
3974
3975 for (start= (char*) arg->ptr(), end= start + arg_length; start < end; )
3976 {
3977 my_wc_t wc;
3978 bool escape;
3979 if ((mblen= cs->cset->mb_wc(cs, &wc, (uchar*) start, (uchar*) end)) <= 0)
3980 goto null;
3981 start+= mblen;
3982 switch (wc) {
3983 case 0: escape= 1; wc= '0'; break;
3984 case '\032': escape= 1; wc= 'Z'; break;
3985 case '\'': escape= 1; break;
3986 case '\\': escape= 1; break;
3987 default: escape= 0; break;
3988 }
3989 if (escape)
3990 {
3991 if ((mblen= cs->cset->wc_mb(cs, '\\', (uchar*) to, to_end)) <= 0)
3992 goto toolong;
3993 to+= mblen;
3994 }
3995 if ((mblen= cs->cset->wc_mb(cs, wc, (uchar*) to, to_end)) <= 0)
3996 goto toolong;
3997 to+= mblen;
3998 }
3999
4000 /* Put trailing quote */
4001 if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
4002 goto toolong;
4003 to+= mblen;
4004 new_length= (uint)(to - str->ptr());
4005 goto ret;
4006 }
4007
4008 /*
4009 We replace characters from the end to the beginning
4010 */
4011 to= (char*) str->ptr() + new_length - 1;
4012 *to--= '\'';
4013 for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
4014 {
4015 /*
4016 We can't use the bitmask here as we want to replace \O and ^Z with 0
4017 and Z
4018 */
4019 switch (*end) {
4020 case 0:
4021 *to--= '0';
4022 *to= '\\';
4023 break;
4024 case '\032':
4025 *to--= 'Z';
4026 *to= '\\';
4027 break;
4028 case '\'':
4029 case '\\':
4030 *to--= *end;
4031 *to= '\\';
4032 break;
4033 default:
4034 *to= *end;
4035 break;
4036 }
4037 }
4038 *to= '\'';
4039
4040ret:
4041 str->length(new_length);
4042 str->set_charset(collation.collation);
4043 null_value= 0;
4044 return str;
4045
4046toolong:
4047 push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
4048 ER_WARN_ALLOWED_PACKET_OVERFLOWED,
4049 ER_THD(current_thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
4050 func_name(), max_allowed_packet);
4051null:
4052 null_value= 1;
4053 return 0;
4054}
4055
4056longlong Item_func_uncompressed_length::val_int()
4057{
4058 DBUG_ASSERT(fixed == 1);
4059 String *res= args[0]->val_str(&value);
4060 if (!res)
4061 {
4062 null_value=1;
4063 return 0; /* purecov: inspected */
4064 }
4065 null_value=0;
4066 if (res->is_empty()) return 0;
4067
4068 /*
4069 If length is <= 4 bytes, data is corrupt. This is the best we can do
4070 to detect garbage input without decompressing it.
4071 */
4072 if (res->length() <= 4)
4073 {
4074 THD *thd= current_thd;
4075 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4076 ER_ZLIB_Z_DATA_ERROR,
4077 ER_THD(thd, ER_ZLIB_Z_DATA_ERROR));
4078 null_value= 1;
4079 return 0;
4080 }
4081
4082 /*
4083 res->ptr() using is safe because we have tested that string is at least
4084 5 bytes long.
4085 res->c_ptr() is not used because:
4086 - we do not need \0 terminated string to get first 4 bytes
4087 - c_ptr() tests simbol after string end (uninitialiozed memory) which
4088 confuse valgrind
4089 */
4090 return uint4korr(res->ptr()) & 0x3FFFFFFF;
4091}
4092
4093longlong Item_func_crc32::val_int()
4094{
4095 DBUG_ASSERT(fixed == 1);
4096 String *res=args[0]->val_str(&value);
4097 if (!res)
4098 {
4099 null_value=1;
4100 return 0; /* purecov: inspected */
4101 }
4102 null_value=0;
4103 return (longlong) my_checksum(0L, (uchar*)res->ptr(), res->length());
4104}
4105
4106#ifdef HAVE_COMPRESS
4107#include "zlib.h"
4108
4109String *Item_func_compress::val_str(String *str)
4110{
4111 int err= Z_OK, code;
4112 size_t new_size;
4113 String *res;
4114 Byte *body;
4115 char *tmp, *last_char;
4116 DBUG_ASSERT(fixed == 1);
4117
4118 if (!(res= args[0]->val_str(&tmp_value)))
4119 {
4120 null_value= 1;
4121 return 0;
4122 }
4123 null_value= 0;
4124 if (res->is_empty()) return res;
4125
4126 /*
4127 Citation from zlib.h (comment for compress function):
4128
4129 Compresses the source buffer into the destination buffer. sourceLen is
4130 the byte length of the source buffer. Upon entry, destLen is the total
4131 size of the destination buffer, which must be at least 0.1% larger than
4132 sourceLen plus 12 bytes.
4133 We assume here that the buffer can't grow more than .25 %.
4134 */
4135 new_size= res->length() + res->length() / 5 + 12;
4136
4137 // Check new_size overflow: new_size <= res->length()
4138 if (((uint32) (new_size+5) <= res->length()) ||
4139 str->realloc((uint32) new_size + 4 + 1))
4140 {
4141 null_value= 1;
4142 return 0;
4143 }
4144
4145 body= ((Byte*)str->ptr()) + 4;
4146
4147 // As far as we have checked res->is_empty() we can use ptr()
4148 if ((err= my_compress_buffer(body, &new_size, (const uchar *)res->ptr(),
4149 res->length())) != Z_OK)
4150 {
4151 THD *thd= current_thd;
4152 code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
4153 push_warning(thd, Sql_condition::WARN_LEVEL_WARN, code,
4154 ER_THD(thd, code));
4155 null_value= 1;
4156 return 0;
4157 }
4158
4159 tmp= (char*) str->ptr(); // int4store is a macro; avoid side effects
4160 int4store(tmp, res->length() & 0x3FFFFFFF);
4161
4162 /* This is to ensure that things works for CHAR fields, which trim ' ': */
4163 last_char= ((char*)body)+new_size-1;
4164 if (*last_char == ' ')
4165 {
4166 *++last_char= '.';
4167 new_size++;
4168 }
4169
4170 str->length((uint32)new_size + 4);
4171 return str;
4172}
4173
4174
4175String *Item_func_uncompress::val_str(String *str)
4176{
4177 DBUG_ASSERT(fixed == 1);
4178 String *res= args[0]->val_str(&tmp_value);
4179 ulong new_size;
4180 int err;
4181 uint code;
4182
4183 if (!res)
4184 goto err;
4185 null_value= 0;
4186 if (res->is_empty())
4187 return res;
4188
4189 /* If length is less than 4 bytes, data is corrupt */
4190 if (res->length() <= 4)
4191 {
4192 THD *thd= current_thd;
4193 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4194 ER_ZLIB_Z_DATA_ERROR,
4195 ER_THD(thd, ER_ZLIB_Z_DATA_ERROR));
4196 goto err;
4197 }
4198
4199 /* Size of uncompressed data is stored as first 4 bytes of field */
4200 new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
4201 if (new_size > current_thd->variables.max_allowed_packet)
4202 {
4203 THD *thd= current_thd;
4204 push_warning_printf(thd,Sql_condition::WARN_LEVEL_WARN,
4205 ER_TOO_BIG_FOR_UNCOMPRESS,
4206 ER_THD(thd, ER_TOO_BIG_FOR_UNCOMPRESS),
4207 static_cast<int>(thd->variables.
4208 max_allowed_packet));
4209 goto err;
4210 }
4211 if (str->realloc((uint32)new_size))
4212 goto err;
4213
4214 if ((err= uncompress((Byte*)str->ptr(), &new_size,
4215 ((const Bytef*)res->ptr())+4,res->length()-4)) == Z_OK)
4216 {
4217 str->length((uint32) new_size);
4218 return str;
4219 }
4220
4221 code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
4222 ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
4223 {
4224 THD *thd= current_thd;
4225 push_warning(thd, Sql_condition::WARN_LEVEL_WARN, code, ER_THD(thd, code));
4226 }
4227
4228err:
4229 null_value= 1;
4230 return 0;
4231}
4232#endif
4233
4234
4235String *Item_func_uuid::val_str(String *str)
4236{
4237 DBUG_ASSERT(fixed == 1);
4238 uchar guid[MY_UUID_SIZE];
4239
4240 str->realloc(MY_UUID_STRING_LENGTH+1);
4241 str->length(MY_UUID_STRING_LENGTH);
4242 str->set_charset(system_charset_info);
4243 my_uuid(guid);
4244 my_uuid2str(guid, (char *)str->ptr());
4245
4246 return str;
4247}
4248
4249
4250Item_func_dyncol_create::Item_func_dyncol_create(THD *thd, List<Item> &args,
4251 DYNCALL_CREATE_DEF *dfs):
4252 Item_str_func(thd, args), defs(dfs), vals(0), keys_num(NULL), keys_str(NULL),
4253 names(FALSE), force_names(FALSE)
4254{
4255 DBUG_ASSERT((args.elements & 0x1) == 0); // even number of arguments
4256}
4257
4258
4259bool Item_func_dyncol_create::fix_fields(THD *thd, Item **ref)
4260{
4261 uint i;
4262 bool res= Item_func::fix_fields(thd, ref); // no need Item_str_func here
4263 if (!res)
4264 {
4265 vals= (DYNAMIC_COLUMN_VALUE *) alloc_root(thd->mem_root,
4266 sizeof(DYNAMIC_COLUMN_VALUE) *
4267 (arg_count / 2));
4268 for (i= 0;
4269 i + 1 < arg_count && args[i]->result_type() == INT_RESULT;
4270 i+= 2)
4271 ;
4272 if (i + 1 < arg_count)
4273 {
4274 names= TRUE;
4275 }
4276
4277 keys_num= (uint *) alloc_root(thd->mem_root,
4278 (sizeof(LEX_STRING) > sizeof(uint) ?
4279 sizeof(LEX_STRING) :
4280 sizeof(uint)) *
4281 (arg_count / 2));
4282 keys_str= (LEX_STRING *) keys_num;
4283 status_var_increment(thd->status_var.feature_dynamic_columns);
4284 }
4285 return res || vals == 0 || keys_num == 0;
4286}
4287
4288
4289void Item_func_dyncol_create::fix_length_and_dec()
4290{
4291 max_length= MAX_BLOB_WIDTH;
4292 maybe_null= TRUE;
4293 collation.set(&my_charset_bin);
4294 decimals= 0;
4295}
4296
4297bool Item_func_dyncol_create::prepare_arguments(THD *thd, bool force_names_arg)
4298{
4299 char buff[STRING_BUFFER_USUAL_SIZE];
4300 String *res, tmp(buff, sizeof(buff), &my_charset_bin);
4301 uint column_count= (arg_count / 2);
4302 uint i;
4303 my_decimal dtmp, *dres;
4304 force_names= force_names_arg;
4305
4306 if (!(names || force_names))
4307 {
4308 for (i= 0; i < column_count; i++)
4309 {
4310 uint valpos= i * 2 + 1;
4311 DYNAMIC_COLUMN_TYPE type= defs[i].type;
4312 if (type == DYN_COL_NULL)
4313 switch (args[valpos]->field_type())
4314 {
4315 case MYSQL_TYPE_VARCHAR:
4316 case MYSQL_TYPE_ENUM:
4317 case MYSQL_TYPE_SET:
4318 case MYSQL_TYPE_TINY_BLOB:
4319 case MYSQL_TYPE_MEDIUM_BLOB:
4320 case MYSQL_TYPE_LONG_BLOB:
4321 case MYSQL_TYPE_BLOB:
4322 case MYSQL_TYPE_VAR_STRING:
4323 case MYSQL_TYPE_STRING:
4324 case MYSQL_TYPE_GEOMETRY:
4325 type= DYN_COL_STRING;
4326 break;
4327 default:
4328 break;
4329 }
4330
4331 if (type == DYN_COL_STRING &&
4332 args[valpos]->type() == Item::FUNC_ITEM &&
4333 ((Item_func *)args[valpos])->functype() == DYNCOL_FUNC)
4334 {
4335 force_names= 1;
4336 break;
4337 }
4338 }
4339 }
4340
4341 /* get values */
4342 for (i= 0; i < column_count; i++)
4343 {
4344 uint valpos= i * 2 + 1;
4345 DYNAMIC_COLUMN_TYPE type= defs[i].type;
4346 if (type == DYN_COL_NULL) // auto detect
4347 {
4348 /*
4349 We don't have a default here to ensure we get a warning if
4350 one adds a new not handled MYSQL_TYPE_...
4351 */
4352 switch (args[valpos]->field_type()) {
4353 case MYSQL_TYPE_DECIMAL:
4354 case MYSQL_TYPE_NEWDECIMAL:
4355 type= DYN_COL_DECIMAL;
4356 break;
4357 case MYSQL_TYPE_TINY:
4358 case MYSQL_TYPE_SHORT:
4359 case MYSQL_TYPE_LONG:
4360 case MYSQL_TYPE_LONGLONG:
4361 case MYSQL_TYPE_INT24:
4362 case MYSQL_TYPE_YEAR:
4363 case MYSQL_TYPE_BIT:
4364 type= args[valpos]->unsigned_flag ? DYN_COL_UINT : DYN_COL_INT;
4365 break;
4366 case MYSQL_TYPE_FLOAT:
4367 case MYSQL_TYPE_DOUBLE:
4368 type= DYN_COL_DOUBLE;
4369 break;
4370 case MYSQL_TYPE_NULL:
4371 type= DYN_COL_NULL;
4372 break;
4373 case MYSQL_TYPE_TIMESTAMP:
4374 case MYSQL_TYPE_TIMESTAMP2:
4375 case MYSQL_TYPE_DATETIME:
4376 case MYSQL_TYPE_DATETIME2:
4377 type= DYN_COL_DATETIME;
4378 break;
4379 case MYSQL_TYPE_DATE:
4380 case MYSQL_TYPE_NEWDATE:
4381 type= DYN_COL_DATE;
4382 break;
4383 case MYSQL_TYPE_TIME:
4384 case MYSQL_TYPE_TIME2:
4385 type= DYN_COL_TIME;
4386 break;
4387 case MYSQL_TYPE_VARCHAR:
4388 case MYSQL_TYPE_ENUM:
4389 case MYSQL_TYPE_SET:
4390 case MYSQL_TYPE_TINY_BLOB:
4391 case MYSQL_TYPE_MEDIUM_BLOB:
4392 case MYSQL_TYPE_LONG_BLOB:
4393 case MYSQL_TYPE_BLOB:
4394 case MYSQL_TYPE_VAR_STRING:
4395 case MYSQL_TYPE_STRING:
4396 case MYSQL_TYPE_GEOMETRY:
4397 type= DYN_COL_STRING;
4398 break;
4399 case MYSQL_TYPE_VARCHAR_COMPRESSED:
4400 case MYSQL_TYPE_BLOB_COMPRESSED:
4401 DBUG_ASSERT(0);
4402 }
4403 }
4404 if (type == DYN_COL_STRING &&
4405 args[valpos]->type() == Item::FUNC_ITEM &&
4406 ((Item_func *)args[valpos])->functype() == DYNCOL_FUNC)
4407 {
4408 DBUG_ASSERT(names || force_names);
4409 type= DYN_COL_DYNCOL;
4410 }
4411 if (names || force_names)
4412 {
4413 res= args[i * 2]->val_str(&tmp);
4414 if (res)
4415 {
4416 // guaranty UTF-8 string for names
4417 if (my_charset_same(res->charset(), DYNCOL_UTF))
4418 {
4419 keys_str[i].length= res->length();
4420 keys_str[i].str= thd->strmake(res->ptr(), res->length());
4421 }
4422 else
4423 {
4424 uint strlen= res->length() * DYNCOL_UTF->mbmaxlen + 1;
4425 uint dummy_errors;
4426 if (char *str= (char *) thd->alloc(strlen))
4427 {
4428 keys_str[i].length=
4429 copy_and_convert(str, strlen, DYNCOL_UTF,
4430 res->ptr(), res->length(), res->charset(),
4431 &dummy_errors);
4432 keys_str[i].str= str;
4433 }
4434 else
4435 keys_str[i].length= 0;
4436
4437 }
4438 }
4439 else
4440 {
4441 keys_str[i].length= 0;
4442 keys_str[i].str= NULL;
4443 }
4444 }
4445 else
4446 keys_num[i]= (uint) args[i * 2]->val_int();
4447 if (args[i * 2]->null_value)
4448 {
4449 /* to make cleanup possible */
4450 for (; i < column_count; i++)
4451 vals[i].type= DYN_COL_NULL;
4452 return 1;
4453 }
4454 vals[i].type= type;
4455 switch (type) {
4456 case DYN_COL_NULL:
4457 DBUG_ASSERT(args[valpos]->field_type() == MYSQL_TYPE_NULL);
4458 break;
4459 case DYN_COL_INT:
4460 vals[i].x.long_value= args[valpos]->val_int();
4461 break;
4462 case DYN_COL_UINT:
4463 vals[i].x.ulong_value= args[valpos]->val_int();
4464 break;
4465 case DYN_COL_DOUBLE:
4466 vals[i].x.double_value= args[valpos]->val_real();
4467 break;
4468 case DYN_COL_DYNCOL:
4469 case DYN_COL_STRING:
4470 res= args[valpos]->val_str(&tmp);
4471 if (res && defs[i].cs)
4472 res->set_charset(defs[i].cs);
4473 if (res &&
4474 (vals[i].x.string.value.str= thd->strmake(res->ptr(), res->length())))
4475 {
4476 vals[i].x.string.value.length= res->length();
4477 vals[i].x.string.charset= res->charset();
4478 }
4479 else
4480 {
4481 args[valpos]->null_value= 1; // In case of out of memory
4482 vals[i].x.string.value.str= NULL;
4483 vals[i].x.string.value.length= 0; // just to be safe
4484 }
4485 break;
4486 case DYN_COL_DECIMAL:
4487 if ((dres= args[valpos]->val_decimal(&dtmp)))
4488 {
4489 mariadb_dyncol_prepare_decimal(&vals[i]);
4490 DBUG_ASSERT(vals[i].x.decimal.value.len == dres->len);
4491 vals[i].x.decimal.value.intg= dres->intg;
4492 vals[i].x.decimal.value.frac= dres->frac;
4493 vals[i].x.decimal.value.sign= dres->sign();
4494 memcpy(vals[i].x.decimal.buffer, dres->buf,
4495 sizeof(vals[i].x.decimal.buffer));
4496 }
4497 else
4498 {
4499 mariadb_dyncol_prepare_decimal(&vals[i]); // just to be safe
4500 DBUG_ASSERT(args[valpos]->null_value);
4501 }
4502 break;
4503 case DYN_COL_DATETIME:
4504 case DYN_COL_DATE:
4505 args[valpos]->get_date(&vals[i].x.time_value,
4506 sql_mode_for_dates(thd));
4507 break;
4508 case DYN_COL_TIME:
4509 args[valpos]->get_time(&vals[i].x.time_value);
4510 break;
4511 default:
4512 DBUG_ASSERT(0);
4513 vals[i].type= DYN_COL_NULL;
4514 }
4515 if (vals[i].type != DYN_COL_NULL && args[valpos]->null_value)
4516 {
4517 vals[i].type= DYN_COL_NULL;
4518 }
4519 }
4520 return FALSE;
4521}
4522
4523
4524String *Item_func_dyncol_create::val_str(String *str)
4525{
4526 DYNAMIC_COLUMN col;
4527 String *res;
4528 uint column_count= (arg_count / 2);
4529 enum enum_dyncol_func_result rc;
4530 DBUG_ASSERT((arg_count & 0x1) == 0); // even number of arguments
4531
4532 /* FIXME: add thd argument to Item::val_str() */
4533 if (prepare_arguments(current_thd, FALSE))
4534 {
4535 res= NULL;
4536 null_value= 1;
4537 }
4538 else
4539 {
4540 if ((rc= ((names || force_names) ?
4541 mariadb_dyncol_create_many_named(&col, column_count, keys_str,
4542 vals, TRUE) :
4543 mariadb_dyncol_create_many_num(&col, column_count, keys_num,
4544 vals, TRUE))))
4545 {
4546 dynamic_column_error_message(rc);
4547 mariadb_dyncol_free(&col);
4548 res= NULL;
4549 null_value= TRUE;
4550 }
4551 else
4552 {
4553 /* Move result from DYNAMIC_COLUMN to str_value */
4554 char *ptr;
4555 size_t length, alloc_length;
4556 dynstr_reassociate(&col, &ptr, &length, &alloc_length);
4557 str_value.reset(ptr, length, alloc_length, &my_charset_bin);
4558 res= &str_value;
4559 null_value= FALSE;
4560 }
4561 }
4562
4563 return res;
4564}
4565
4566void Item_func_dyncol_create::print_arguments(String *str,
4567 enum_query_type query_type)
4568{
4569 uint i;
4570 uint column_count= (arg_count / 2);
4571 for (i= 0; i < column_count; i++)
4572 {
4573 args[i*2]->print(str, query_type);
4574 str->append(',');
4575 args[i*2 + 1]->print(str, query_type);
4576 switch (defs[i].type) {
4577 case DYN_COL_NULL: // automatic type => write nothing
4578 break;
4579 case DYN_COL_INT:
4580 str->append(STRING_WITH_LEN(" AS int"));
4581 break;
4582 case DYN_COL_UINT:
4583 str->append(STRING_WITH_LEN(" AS unsigned int"));
4584 break;
4585 case DYN_COL_DOUBLE:
4586 str->append(STRING_WITH_LEN(" AS double"));
4587 break;
4588 case DYN_COL_DYNCOL:
4589 case DYN_COL_STRING:
4590 str->append(STRING_WITH_LEN(" AS char"));
4591 if (defs[i].cs)
4592 {
4593 str->append(STRING_WITH_LEN(" charset "));
4594 str->append(defs[i].cs->csname);
4595 str->append(' ');
4596 }
4597 break;
4598 case DYN_COL_DECIMAL:
4599 str->append(STRING_WITH_LEN(" AS decimal"));
4600 break;
4601 case DYN_COL_DATETIME:
4602 str->append(STRING_WITH_LEN(" AS datetime"));
4603 break;
4604 case DYN_COL_DATE:
4605 str->append(STRING_WITH_LEN(" AS date"));
4606 break;
4607 case DYN_COL_TIME:
4608 str->append(STRING_WITH_LEN(" AS time"));
4609 break;
4610 }
4611 if (i < column_count - 1)
4612 str->append(',');
4613 }
4614}
4615
4616
4617void Item_func_dyncol_create::print(String *str,
4618 enum_query_type query_type)
4619{
4620 DBUG_ASSERT((arg_count & 0x1) == 0); // even number of arguments
4621 str->append(STRING_WITH_LEN("column_create("));
4622 print_arguments(str, query_type);
4623 str->append(')');
4624}
4625
4626String *Item_func_dyncol_json::val_str(String *str)
4627{
4628 DYNAMIC_STRING json, col;
4629 String *res;
4630 enum enum_dyncol_func_result rc;
4631
4632 res= args[0]->val_str(str);
4633 if (args[0]->null_value)
4634 goto null;
4635
4636 col.str= (char *)res->ptr();
4637 col.length= res->length();
4638 if ((rc= mariadb_dyncol_json(&col, &json)))
4639 {
4640 dynamic_column_error_message(rc);
4641 goto null;
4642 }
4643 bzero(&col, sizeof(col));
4644 {
4645 /* Move result from DYNAMIC_COLUMN to str */
4646 char *ptr;
4647 size_t length, alloc_length;
4648 dynstr_reassociate(&json, &ptr, &length, &alloc_length);
4649 str->reset(ptr, length, alloc_length, DYNCOL_UTF);
4650 null_value= FALSE;
4651 }
4652 str->set_charset(DYNCOL_UTF);
4653 return str;
4654
4655null:
4656 bzero(&col, sizeof(col));
4657 null_value= TRUE;
4658 return NULL;
4659}
4660
4661String *Item_func_dyncol_add::val_str(String *str)
4662{
4663 DYNAMIC_COLUMN col;
4664 String *res;
4665 uint column_count= (arg_count / 2);
4666 enum enum_dyncol_func_result rc;
4667 DBUG_ASSERT((arg_count & 0x1) == 1); // odd number of arguments
4668
4669 /* We store the packed data last */
4670 res= args[arg_count - 1]->val_str(str);
4671 if (args[arg_count - 1]->null_value ||
4672 init_dynamic_string(&col, NULL, res->length() + STRING_BUFFER_USUAL_SIZE,
4673 STRING_BUFFER_USUAL_SIZE))
4674 goto null;
4675
4676 col.length= res->length();
4677 memcpy(col.str, res->ptr(), col.length);
4678
4679 /* FIXME: add thd argument to Item::val_str() */
4680 if (prepare_arguments(current_thd, mariadb_dyncol_has_names(&col)))
4681 goto null;
4682
4683 if ((rc= ((names || force_names) ?
4684 mariadb_dyncol_update_many_named(&col, column_count,
4685 keys_str, vals) :
4686 mariadb_dyncol_update_many_num(&col, column_count,
4687 keys_num, vals))))
4688 {
4689 dynamic_column_error_message(rc);
4690 mariadb_dyncol_free(&col);
4691 goto null;
4692 }
4693
4694 {
4695 /* Move result from DYNAMIC_COLUMN to str */
4696 char *ptr;
4697 size_t length, alloc_length;
4698 dynstr_reassociate(&col, &ptr, &length, &alloc_length);
4699 str->reset(ptr, length, alloc_length, &my_charset_bin);
4700 null_value= FALSE;
4701 }
4702
4703 return str;
4704
4705null:
4706 null_value= TRUE;
4707 return NULL;
4708}
4709
4710
4711void Item_func_dyncol_add::print(String *str,
4712 enum_query_type query_type)
4713{
4714 DBUG_ASSERT((arg_count & 0x1) == 1); // odd number of arguments
4715 str->append(STRING_WITH_LEN("column_add("));
4716 args[arg_count - 1]->print(str, query_type);
4717 str->append(',');
4718 print_arguments(str, query_type);
4719 str->append(')');
4720}
4721
4722
4723/**
4724 Get value for a column stored in a dynamic column
4725
4726 @notes
4727 This function ensures that null_value is set correctly
4728*/
4729
4730bool Item_dyncol_get::get_dyn_value(THD *thd, DYNAMIC_COLUMN_VALUE *val,
4731 String *tmp)
4732{
4733 DYNAMIC_COLUMN dyn_str;
4734 String *res;
4735 longlong num= 0;
4736 LEX_STRING buf, *name= NULL;
4737 char nmstrbuf[11];
4738 String nmbuf(nmstrbuf, sizeof(nmstrbuf), system_charset_info);
4739 enum enum_dyncol_func_result rc;
4740
4741 if (args[1]->result_type() == INT_RESULT)
4742 num= args[1]->val_int();
4743 else
4744 {
4745 String *nm= args[1]->val_str(&nmbuf);
4746 if (!nm || args[1]->null_value)
4747 {
4748 null_value= 1;
4749 return 1;
4750 }
4751
4752 if (my_charset_same(nm->charset(), DYNCOL_UTF))
4753 {
4754 buf.str= (char *) nm->ptr();
4755 buf.length= nm->length();
4756 }
4757 else
4758 {
4759 uint strlen= nm->length() * DYNCOL_UTF->mbmaxlen + 1;
4760 uint dummy_errors;
4761 buf.str= (char *) thd->alloc(strlen);
4762 if (buf.str)
4763 {
4764 buf.length=
4765 copy_and_convert(buf.str, strlen, DYNCOL_UTF,
4766 nm->ptr(), nm->length(), nm->charset(),
4767 &dummy_errors);
4768 }
4769 else
4770 buf.length= 0;
4771 }
4772 name= &buf;
4773 }
4774
4775
4776 if (args[1]->null_value || num < 0 || num > INT_MAX)
4777 {
4778 null_value= 1;
4779 return 1;
4780 }
4781
4782 res= args[0]->val_str(tmp);
4783 if (args[0]->null_value)
4784 {
4785 null_value= 1;
4786 return 1;
4787 }
4788
4789 dyn_str.str= (char*) res->ptr();
4790 dyn_str.length= res->length();
4791 if ((rc= ((name == NULL) ?
4792 mariadb_dyncol_get_num(&dyn_str, (uint) num, val) :
4793 mariadb_dyncol_get_named(&dyn_str, name, val))))
4794 {
4795 dynamic_column_error_message(rc);
4796 null_value= 1;
4797 return 1;
4798 }
4799
4800 null_value= 0;
4801 return 0; // ok
4802}
4803
4804
4805String *Item_dyncol_get::val_str(String *str_result)
4806{
4807 DYNAMIC_COLUMN_VALUE val;
4808 char buff[STRING_BUFFER_USUAL_SIZE];
4809 String tmp(buff, sizeof(buff), &my_charset_bin);
4810
4811 if (get_dyn_value(current_thd, &val, &tmp))
4812 return NULL;
4813
4814 switch (val.type) {
4815 case DYN_COL_NULL:
4816 goto null;
4817 case DYN_COL_INT:
4818 case DYN_COL_UINT:
4819 str_result->set_int(val.x.long_value, MY_TEST(val.type == DYN_COL_UINT),
4820 &my_charset_latin1);
4821 break;
4822 case DYN_COL_DOUBLE:
4823 str_result->set_real(val.x.double_value, NOT_FIXED_DEC, &my_charset_latin1);
4824 break;
4825 case DYN_COL_DYNCOL:
4826 case DYN_COL_STRING:
4827 if ((char*) tmp.ptr() <= val.x.string.value.str &&
4828 (char*) tmp.ptr() + tmp.length() >= val.x.string.value.str)
4829 {
4830 /* value is allocated in tmp buffer; We have to make a copy */
4831 str_result->copy(val.x.string.value.str, val.x.string.value.length,
4832 val.x.string.charset);
4833 }
4834 else
4835 {
4836 /*
4837 It's safe to use the current value because it's either pointing
4838 into a field or in a buffer for another item and this buffer
4839 is not going to be deleted during expression evaluation
4840 */
4841 str_result->set(val.x.string.value.str, val.x.string.value.length,
4842 val.x.string.charset);
4843 }
4844 break;
4845 case DYN_COL_DECIMAL:
4846 {
4847 int res;
4848 int length= decimal_string_size(&val.x.decimal.value);
4849 if (str_result->alloc(length))
4850 goto null;
4851 if ((res= decimal2string(&val.x.decimal.value, (char*) str_result->ptr(),
4852 &length, 0, 0, ' ')) != E_DEC_OK)
4853 {
4854 char buff[40];
4855 int len= sizeof(buff);
4856 DBUG_ASSERT(length < (int)sizeof(buff));
4857 decimal2string(&val.x.decimal.value, buff, &len, 0, 0, ' ');
4858 decimal_operation_results(res, buff, "CHAR");
4859 }
4860 str_result->set_charset(&my_charset_latin1);
4861 str_result->length(length);
4862 break;
4863 }
4864 case DYN_COL_DATETIME:
4865 case DYN_COL_DATE:
4866 case DYN_COL_TIME:
4867 {
4868 int length;
4869 /*
4870 We use AUTO_SEC_PART_DIGITS here to ensure that we do not loose
4871 any microseconds from the data. This is safe to do as we are
4872 asked to return the time argument as a string.
4873 */
4874 if (str_result->alloc(MAX_DATE_STRING_REP_LENGTH) ||
4875 !(length= my_TIME_to_str(&val.x.time_value, (char*) str_result->ptr(),
4876 AUTO_SEC_PART_DIGITS)))
4877 goto null;
4878 str_result->set_charset(&my_charset_latin1);
4879 str_result->length(length);
4880 break;
4881 }
4882 }
4883 return str_result;
4884
4885null:
4886 null_value= TRUE;
4887 return 0;
4888}
4889
4890
4891longlong Item_dyncol_get::val_int()
4892{
4893 THD *thd= current_thd;
4894 DYNAMIC_COLUMN_VALUE val;
4895 char buff[STRING_BUFFER_USUAL_SIZE];
4896 String tmp(buff, sizeof(buff), &my_charset_bin);
4897
4898 if (get_dyn_value(thd, &val, &tmp))
4899 return 0;
4900
4901 switch (val.type) {
4902 case DYN_COL_DYNCOL:
4903 case DYN_COL_NULL:
4904 goto null;
4905 case DYN_COL_UINT:
4906 unsigned_flag= 1; // Make it possible for caller to detect sign
4907 return val.x.long_value;
4908 case DYN_COL_INT:
4909 unsigned_flag= 0; // Make it possible for caller to detect sign
4910 return val.x.long_value;
4911 case DYN_COL_DOUBLE:
4912 return Converter_double_to_longlong_with_warn(thd, val.x.double_value,
4913 unsigned_flag).result();
4914 case DYN_COL_STRING:
4915 {
4916 int error;
4917 longlong num;
4918 char *end= val.x.string.value.str + val.x.string.value.length, *org_end= end;
4919
4920 num= my_strtoll10(val.x.string.value.str, &end, &error);
4921 if (unlikely(end != org_end || error > 0))
4922 {
4923 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4924 ER_BAD_DATA,
4925 ER_THD(thd, ER_BAD_DATA),
4926 ErrConvString(val.x.string.value.str,
4927 val.x.string.value.length,
4928 val.x.string.charset).ptr(),
4929 unsigned_flag ? "UNSIGNED INT" : "INT");
4930 }
4931 unsigned_flag= error >= 0;
4932 return num;
4933 }
4934 case DYN_COL_DECIMAL:
4935 {
4936 longlong num;
4937 my_decimal2int(E_DEC_FATAL_ERROR, &val.x.decimal.value, unsigned_flag,
4938 &num);
4939 return num;
4940 }
4941 case DYN_COL_DATETIME:
4942 case DYN_COL_DATE:
4943 case DYN_COL_TIME:
4944 unsigned_flag= !val.x.time_value.neg;
4945 if (unsigned_flag)
4946 return TIME_to_ulonglong(&val.x.time_value);
4947 else
4948 return -(longlong)TIME_to_ulonglong(&val.x.time_value);
4949 }
4950
4951null:
4952 null_value= TRUE;
4953 return 0;
4954}
4955
4956
4957double Item_dyncol_get::val_real()
4958{
4959 THD *thd= current_thd;
4960 DYNAMIC_COLUMN_VALUE val;
4961 char buff[STRING_BUFFER_USUAL_SIZE];
4962 String tmp(buff, sizeof(buff), &my_charset_bin);
4963
4964 if (get_dyn_value(thd, &val, &tmp))
4965 return 0.0;
4966
4967 switch (val.type) {
4968 case DYN_COL_DYNCOL:
4969 case DYN_COL_NULL:
4970 goto null;
4971 case DYN_COL_UINT:
4972 return ulonglong2double(val.x.ulong_value);
4973 case DYN_COL_INT:
4974 return (double) val.x.long_value;
4975 case DYN_COL_DOUBLE:
4976 return (double) val.x.double_value;
4977 case DYN_COL_STRING:
4978 {
4979 int error;
4980 char *end;
4981 double res= my_strntod(val.x.string.charset, (char*) val.x.string.value.str,
4982 val.x.string.value.length, &end, &error);
4983
4984 if (end != (char*) val.x.string.value.str + val.x.string.value.length ||
4985 error)
4986 {
4987 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4988 ER_BAD_DATA,
4989 ER_THD(thd, ER_BAD_DATA),
4990 ErrConvString(val.x.string.value.str,
4991 val.x.string.value.length,
4992 val.x.string.charset).ptr(),
4993 "DOUBLE");
4994 }
4995 return res;
4996 }
4997 case DYN_COL_DECIMAL:
4998 {
4999 double res;
5000 /* This will always succeed */
5001 decimal2double(&val.x.decimal.value, &res);
5002 return res;
5003 }
5004 case DYN_COL_DATETIME:
5005 case DYN_COL_DATE:
5006 case DYN_COL_TIME:
5007 return TIME_to_double(&val.x.time_value);
5008 }
5009
5010null:
5011 null_value= TRUE;
5012 return 0.0;
5013}
5014
5015
5016my_decimal *Item_dyncol_get::val_decimal(my_decimal *decimal_value)
5017{
5018 THD *thd= current_thd;
5019 DYNAMIC_COLUMN_VALUE val;
5020 char buff[STRING_BUFFER_USUAL_SIZE];
5021 String tmp(buff, sizeof(buff), &my_charset_bin);
5022
5023 if (get_dyn_value(thd, &val, &tmp))
5024 return NULL;
5025
5026 switch (val.type) {
5027 case DYN_COL_DYNCOL:
5028 case DYN_COL_NULL:
5029 goto null;
5030 case DYN_COL_UINT:
5031 int2my_decimal(E_DEC_FATAL_ERROR, val.x.long_value, TRUE, decimal_value);
5032 break;
5033 case DYN_COL_INT:
5034 int2my_decimal(E_DEC_FATAL_ERROR, val.x.long_value, FALSE, decimal_value);
5035 break;
5036 case DYN_COL_DOUBLE:
5037 double2my_decimal(E_DEC_FATAL_ERROR, val.x.double_value, decimal_value);
5038 break;
5039 case DYN_COL_STRING:
5040 {
5041 const char *end;
5042 int rc;
5043 rc= str2my_decimal(0, val.x.string.value.str, val.x.string.value.length,
5044 val.x.string.charset, decimal_value, &end);
5045 if (rc != E_DEC_OK ||
5046 end != val.x.string.value.str + val.x.string.value.length)
5047 {
5048 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
5049 ER_BAD_DATA,
5050 ER_THD(thd, ER_BAD_DATA),
5051 ErrConvString(val.x.string.value.str,
5052 val.x.string.value.length,
5053 val.x.string.charset).ptr(),
5054 "DECIMAL");
5055 }
5056 break;
5057 }
5058 case DYN_COL_DECIMAL:
5059 decimal2my_decimal(&val.x.decimal.value, decimal_value);
5060 break;
5061 case DYN_COL_DATETIME:
5062 case DYN_COL_DATE:
5063 case DYN_COL_TIME:
5064 decimal_value= TIME_to_my_decimal(&val.x.time_value, decimal_value);
5065 break;
5066 }
5067 return decimal_value;
5068
5069null:
5070 null_value= TRUE;
5071 return 0;
5072}
5073
5074
5075bool Item_dyncol_get::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
5076{
5077 DYNAMIC_COLUMN_VALUE val;
5078 char buff[STRING_BUFFER_USUAL_SIZE];
5079 String tmp(buff, sizeof(buff), &my_charset_bin);
5080 bool signed_value= 0;
5081
5082 if (get_dyn_value(current_thd, &val, &tmp))
5083 return 1; // Error
5084
5085 switch (val.type) {
5086 case DYN_COL_DYNCOL:
5087 case DYN_COL_NULL:
5088 goto null;
5089 case DYN_COL_INT:
5090 signed_value= 1; // For error message
5091 /* fall through */
5092 case DYN_COL_UINT:
5093 if (signed_value || val.x.ulong_value <= LONGLONG_MAX)
5094 {
5095 longlong llval = (longlong)val.x.ulong_value;
5096 bool neg = llval < 0;
5097 if (int_to_datetime_with_warn(neg, (ulonglong)(neg ? -llval :
5098 llval),
5099 ltime, fuzzy_date, 0 /* TODO */))
5100 goto null;
5101 return 0;
5102 }
5103 /* let double_to_datetime_with_warn() issue the warning message */
5104 val.x.double_value= static_cast<double>(ULONGLONG_MAX);
5105 /* fall through */
5106 case DYN_COL_DOUBLE:
5107 if (double_to_datetime_with_warn(val.x.double_value, ltime, fuzzy_date,
5108 0 /* TODO */))
5109 goto null;
5110 return 0;
5111 case DYN_COL_DECIMAL:
5112 if (decimal_to_datetime_with_warn((my_decimal*)&val.x.decimal.value, ltime,
5113 fuzzy_date, 0 /* TODO */))
5114 goto null;
5115 return 0;
5116 case DYN_COL_STRING:
5117 if (str_to_datetime_with_warn(&my_charset_numeric,
5118 val.x.string.value.str,
5119 val.x.string.value.length,
5120 ltime, fuzzy_date))
5121 goto null;
5122 return 0;
5123 case DYN_COL_DATETIME:
5124 case DYN_COL_DATE:
5125 case DYN_COL_TIME:
5126 *ltime= val.x.time_value;
5127 return 0;
5128 }
5129
5130null:
5131 null_value= TRUE;
5132 return 1;
5133}
5134
5135void Item_dyncol_get::print(String *str, enum_query_type query_type)
5136{
5137 /*
5138 Parent cast doesn't exist yet, only print dynamic column name. This happens
5139 when called from create_func_cast() / wrong_precision_error().
5140 */
5141 if (!str->length())
5142 {
5143 args[1]->print(str, query_type);
5144 return;
5145 }
5146
5147 /* see create_func_dyncol_get */
5148 DBUG_ASSERT(str->length() >= 5);
5149 DBUG_ASSERT(strncmp(str->ptr() + str->length() - 5, "cast(", 5) == 0);
5150
5151 str->length(str->length() - 5); // removing "cast("
5152 str->append(STRING_WITH_LEN("column_get("));
5153 args[0]->print(str, query_type);
5154 str->append(',');
5155 args[1]->print(str, query_type);
5156 /* let the parent cast item add " as <type>)" */
5157}
5158
5159
5160String *Item_func_dyncol_list::val_str(String *str)
5161{
5162 uint i;
5163 enum enum_dyncol_func_result rc;
5164 LEX_STRING *names= 0;
5165 uint count;
5166 DYNAMIC_COLUMN col;
5167 String *res= args[0]->val_str(str);
5168
5169 if (args[0]->null_value)
5170 goto null;
5171 col.length= res->length();
5172 /* We do not change the string, so could do this trick */
5173 col.str= (char *)res->ptr();
5174 if ((rc= mariadb_dyncol_list_named(&col, &count, &names)))
5175 {
5176 bzero(&col, sizeof(col));
5177 dynamic_column_error_message(rc);
5178 goto null;
5179 }
5180 bzero(&col, sizeof(col));
5181
5182 /*
5183 We estimate average name length as 10
5184 */
5185 if (str->alloc(count * 13))
5186 goto null;
5187
5188 str->length(0);
5189 for (i= 0; i < count; i++)
5190 {
5191 append_identifier(current_thd, str, names[i].str, names[i].length);
5192 if (i < count - 1)
5193 str->qs_append(',');
5194 }
5195 null_value= FALSE;
5196 if (names)
5197 my_free(names);
5198 str->set_charset(DYNCOL_UTF);
5199 return str;
5200
5201null:
5202 null_value= TRUE;
5203 if (names)
5204 my_free(names);
5205 return NULL;
5206}
5207
5208Item_temptable_rowid::Item_temptable_rowid(TABLE *table_arg)
5209 : Item_str_func(table_arg->in_use), table(table_arg)
5210{
5211 max_length= table->file->ref_length;
5212}
5213
5214void Item_temptable_rowid::fix_length_and_dec()
5215{
5216 used_tables_cache= table->map;
5217 const_item_cache= false;
5218}
5219
5220String *Item_temptable_rowid::val_str(String *str)
5221{
5222 if (!((null_value= table->null_row)))
5223 table->file->position(table->record[0]);
5224 str_value.set((char*)(table->file->ref), max_length, &my_charset_bin);
5225 return &str_value;
5226}
5227