1
/* Copyright (C) 2000-2006 MySQL AB
3
This program is free software; you can redistribute it and/or modify
4
it under the terms of the GNU General Public License as published by
5
the Free Software Foundation; version 2 of the License.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
21
This file defines all string functions
24
Some string functions don't always put and end-null on a String.
25
(This shouldn't be needed)
28
#ifdef USE_PRAGMA_IMPLEMENTATION
29
#pragma implementation // gcc: Class implementation
33
#include "mysql_priv.h"
40
#include "../mysys/my_static.h" // For soundex_map
43
String my_empty_string("",default_charset_info);
48
bool Item_str_func::fix_fields(THD *thd, Item **ref)
50
bool res= Item_func::fix_fields(thd, ref);
52
In Item_str_func::check_well_formed_result() we may set null_value
53
flag on the same condition as in test() below.
55
maybe_null= (maybe_null ||
56
test(thd->variables.sql_mode &
57
(MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)));
62
my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
66
String *res, tmp(buff,sizeof(buff), &my_charset_bin);
70
(void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
71
res->length(), res->charset(), decimal_value);
76
double Item_str_func::val_real()
80
char *end_not_used, buff[64];
81
String *res, tmp(buff,sizeof(buff), &my_charset_bin);
83
return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
84
&end_not_used, &err_not_used) : 0.0;
88
longlong Item_str_func::val_int()
93
String *res, tmp(buff,sizeof(buff), &my_charset_bin);
96
my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL,
102
String *Item_func_md5::val_str(String *str)
105
String * sptr= args[0]->val_str(str);
106
str->set_charset(&my_charset_bin);
113
my_MD5Init (&context);
114
my_MD5Update (&context,(uchar *) sptr->ptr(), sptr->length());
115
my_MD5Final (digest, &context);
116
if (str->alloc(32)) // Ensure that memory is free
121
sprintf((char *) str->ptr(),
122
"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
123
digest[0], digest[1], digest[2], digest[3],
124
digest[4], digest[5], digest[6], digest[7],
125
digest[8], digest[9], digest[10], digest[11],
126
digest[12], digest[13], digest[14], digest[15]);
127
str->length((uint) 32);
135
void Item_func_md5::fix_length_and_dec()
139
The MD5() function treats its parameter as being a case sensitive. Thus
140
we set binary collation on it so different instances of MD5() will be
143
args[0]->collation.set(
144
get_charset_by_csname(args[0]->collation.collation->csname,
145
MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
149
Concatenate args with the following premises:
150
If only one arg (which is ok), return value of arg;
151
Don't reallocate val_str() if not absolute necessary.
154
String *Item_func_concat::val_str(String *str)
157
String *res,*res2,*use_as_buff;
162
if (!(res=args[0]->val_str(str)))
164
use_as_buff= &tmp_value;
165
/* Item_subselect in --ps-protocol mode will state it as a non-const */
166
is_const= args[0]->const_item() || !args[0]->used_tables();
167
for (i=1 ; i < arg_count ; i++)
169
if (res->length() == 0)
171
if (!(res=args[i]->val_str(str)))
176
if (!(res2=args[i]->val_str(use_as_buff)))
178
if (res2->length() == 0)
180
if (res->length()+res2->length() >
181
current_thd->variables.max_allowed_packet)
183
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
184
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
185
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
186
current_thd->variables.max_allowed_packet);
189
if (!is_const && res->alloced_length() >= res->length()+res2->length())
193
else if (str->alloced_length() >= res->length()+res2->length())
196
str->replace(0,0,*res);
203
use_as_buff= &tmp_value;
205
else if (res == &tmp_value)
207
if (res->append(*res2)) // Must be a blob
210
else if (res2 == &tmp_value)
211
{ // This can happend only 1 time
212
if (tmp_value.replace(0,0,*res))
215
use_as_buff=str; // Put next arg here
217
else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
218
res2->ptr() <= tmp_value.ptr() + tmp_value.alloced_length())
221
This happens really seldom:
222
In this case res2 is sub string of tmp_value. We will
223
now work in place in tmp_value to set it to res | res2
225
/* Chop the last characters in tmp_value that isn't in res2 */
226
tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
228
/* Place res2 at start of tmp_value, remove chars before res2 */
229
if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
233
use_as_buff=str; // Put next arg here
236
{ // Two big const strings
238
NOTE: We should be prudent in the initial allocation unit -- the
239
size of the arguments is a function of data distribution, which
240
can be any. Instead of overcommitting at the first row, we grow
241
the allocated amount by the factor of 2. This ensures that no
242
more than 25% of memory will be overcommitted on average.
245
uint concat_len= res->length() + res2->length();
247
if (tmp_value.alloced_length() < concat_len)
249
if (tmp_value.alloced_length() == 0)
251
if (tmp_value.alloc(concat_len))
256
uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
258
if (tmp_value.realloc(new_len))
263
if (tmp_value.copy(*res) || tmp_value.append(*res2))
272
res->set_charset(collation.collation);
281
void Item_func_concat::fix_length_and_dec()
283
ulonglong max_result_length= 0;
285
if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
288
for (uint i=0 ; i < arg_count ; i++)
290
if (args[i]->collation.collation->mbmaxlen != collation.collation->mbmaxlen)
291
max_result_length+= (args[i]->max_length /
292
args[i]->collation.collation->mbmaxlen) *
293
collation.collation->mbmaxlen;
295
max_result_length+= args[i]->max_length;
298
if (max_result_length >= MAX_BLOB_WIDTH)
300
max_result_length= MAX_BLOB_WIDTH;
303
max_length= (ulong) max_result_length;
308
concat with separator. First arg is the separator
309
concat_ws takes at least two arguments.
312
String *Item_func_concat_ws::val_str(String *str)
315
char tmp_str_buff[10];
316
String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
317
*sep_str, *res, *res2,*use_as_buff;
321
if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
324
use_as_buff= &tmp_value;
325
str->length(0); // QQ; Should be removed
328
// Skip until non-null argument is found.
329
// If not, return the empty string
330
for (i=1; i < arg_count; i++)
331
if ((res= args[i]->val_str(str)))
334
return &my_empty_string;
336
for (i++; i < arg_count ; i++)
338
if (!(res2= args[i]->val_str(use_as_buff)))
339
continue; // Skip NULL
341
if (res->length() + sep_str->length() + res2->length() >
342
current_thd->variables.max_allowed_packet)
344
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
345
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
346
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
347
current_thd->variables.max_allowed_packet);
350
if (res->alloced_length() >=
351
res->length() + sep_str->length() + res2->length())
353
res->append(*sep_str); // res->length() > 0 always
356
else if (str->alloced_length() >=
357
res->length() + sep_str->length() + res2->length())
359
/* We have room in str; We can't get any errors here */
361
{ // This is quote uncommon!
362
str->replace(0,0,*sep_str);
363
str->replace(0,0,*res);
368
str->append(*sep_str);
372
use_as_buff= &tmp_value;
374
else if (res == &tmp_value)
376
if (res->append(*sep_str) || res->append(*res2))
377
goto null; // Must be a blob
379
else if (res2 == &tmp_value)
380
{ // This can happend only 1 time
381
if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res))
384
use_as_buff=str; // Put next arg here
386
else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
387
res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
390
This happens really seldom:
391
In this case res2 is sub string of tmp_value. We will
392
now work in place in tmp_value to set it to res | sep_str | res2
394
/* Chop the last characters in tmp_value that isn't in res2 */
395
tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
397
/* Place res2 at start of tmp_value, remove chars before res2 */
398
if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
400
tmp_value.replace(res->length(),0, *sep_str))
403
use_as_buff=str; // Put next arg here
406
{ // Two big const strings
408
NOTE: We should be prudent in the initial allocation unit -- the
409
size of the arguments is a function of data distribution, which can
410
be any. Instead of overcommitting at the first row, we grow the
411
allocated amount by the factor of 2. This ensures that no more than
412
25% of memory will be overcommitted on average.
415
uint concat_len= res->length() + sep_str->length() + res2->length();
417
if (tmp_value.alloced_length() < concat_len)
419
if (tmp_value.alloced_length() == 0)
421
if (tmp_value.alloc(concat_len))
426
uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
428
if (tmp_value.realloc(new_len))
433
if (tmp_value.copy(*res) ||
434
tmp_value.append(*sep_str) ||
435
tmp_value.append(*res2))
441
res->set_charset(collation.collation);
450
void Item_func_concat_ws::fix_length_and_dec()
452
ulonglong max_result_length;
454
if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
458
arg_count cannot be less than 2,
459
it is done on parser level in sql_yacc.yy
460
so, (arg_count - 2) is safe here.
462
max_result_length= (ulonglong) args[0]->max_length * (arg_count - 2);
463
for (uint i=1 ; i < arg_count ; i++)
464
max_result_length+=args[i]->max_length;
466
if (max_result_length >= MAX_BLOB_WIDTH)
468
max_result_length= MAX_BLOB_WIDTH;
471
max_length= (ulong) max_result_length;
475
String *Item_func_reverse::val_str(String *str)
478
String *res = args[0]->val_str(str);
479
char *ptr, *end, *tmp;
481
if ((null_value=args[0]->null_value))
483
/* An empty string is a special case as the string pointer may be null */
485
return &my_empty_string;
486
if (tmp_value.alloced_length() < res->length() &&
487
tmp_value.realloc(res->length()))
492
tmp_value.length(res->length());
493
tmp_value.set_charset(res->charset());
494
ptr= (char *) res->ptr();
495
end= ptr + res->length();
496
tmp= (char *) tmp_value.ptr() + tmp_value.length();
498
if (use_mb(res->charset()))
503
if ((l= my_ismbchar(res->charset(),ptr,end)))
523
void Item_func_reverse::fix_length_and_dec()
525
collation.set(args[0]->collation);
526
max_length = args[0]->max_length;
530
Replace all occurences of string2 in string1 with string3.
532
Don't reallocate val_str() if not needed.
535
Fix that this works with binary strings when using USE_MB
538
String *Item_func_replace::val_str(String *str)
541
String *res,*res2,*res3;
543
uint from_length,to_length;
546
const char *ptr,*end,*strend,*search,*search_end;
552
res=args[0]->val_str(str);
553
if (args[0]->null_value)
555
res2=args[1]->val_str(&tmp_value);
556
if (args[1]->null_value)
559
res->set_charset(collation.collation);
562
binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
565
if (res2->length() == 0)
568
if ((offset=res->strstr(*res2)) < 0)
572
if (binary_cmp && (offset=res->strstr(*res2)) < 0)
575
if (!(res3=args[2]->val_str(&tmp_value2)))
577
from_length= res2->length();
578
to_length= res3->length();
584
search_end=search+from_length;
586
ptr=res->ptr()+offset;
587
strend=res->ptr()+res->length();
588
end=strend-from_length+1;
594
i=(char*) ptr+1; j=(char*) search+1;
595
while (j != search_end)
596
if (*i++ != *j++) goto skip;
597
offset= (int) (ptr-res->ptr());
598
if (res->length()-from_length + to_length >
599
current_thd->variables.max_allowed_packet)
601
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
602
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
603
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
605
current_thd->variables.max_allowed_packet);
612
res=copy_if_not_alloced(str,res,res->length()+to_length);
614
res->replace((uint) offset,from_length,*res3);
615
offset+=(int) to_length;
619
if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
627
if (res->length()-from_length + to_length >
628
current_thd->variables.max_allowed_packet)
630
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
631
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
632
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
633
current_thd->variables.max_allowed_packet);
639
res=copy_if_not_alloced(str,res,res->length()+to_length);
641
res->replace((uint) offset,from_length,*res3);
642
offset+=(int) to_length;
644
while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
653
void Item_func_replace::fix_length_and_dec()
655
ulonglong max_result_length= args[0]->max_length;
656
int diff=(int) (args[2]->max_length - args[1]->max_length);
657
if (diff > 0 && args[1]->max_length)
658
{ // Calculate of maxreplaces
659
ulonglong max_substrs= max_result_length/args[1]->max_length;
660
max_result_length+= max_substrs * (uint) diff;
662
if (max_result_length >= MAX_BLOB_WIDTH)
664
max_result_length= MAX_BLOB_WIDTH;
667
max_length= (ulong) max_result_length;
669
if (agg_arg_charsets(collation, args, 3, MY_COLL_CMP_CONV, 1))
674
String *Item_func_insert::val_str(String *str)
678
longlong start, length; /* must be longlong to avoid truncation */
681
res=args[0]->val_str(str);
682
res2=args[3]->val_str(&tmp_value);
683
start= args[1]->val_int() - 1;
684
length= args[2]->val_int();
686
if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
688
goto null; /* purecov: inspected */
690
if ((start < 0) || (start > res->length()))
691
return res; // Wrong param; skip insert
692
if ((length < 0) || (length > res->length()))
693
length= res->length();
695
/* start and length are now sufficiently valid to pass to charpos function */
696
start= res->charpos((int) start);
697
length= res->charpos((int) length, (uint32) start);
699
/* Re-testing with corrected params */
700
if (start > res->length())
701
return res; /* purecov: inspected */ // Wrong param; skip insert
702
if (length > res->length() - start)
703
length= res->length() - start;
705
if ((ulonglong) (res->length() - length + res2->length()) >
706
(ulonglong) current_thd->variables.max_allowed_packet)
708
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
709
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
710
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
711
func_name(), current_thd->variables.max_allowed_packet);
714
res=copy_if_not_alloced(str,res,res->length());
715
res->replace((uint32) start,(uint32) length,*res2);
723
void Item_func_insert::fix_length_and_dec()
725
ulonglong max_result_length;
727
// Handle character set for args[0] and args[3].
728
if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 3))
730
max_result_length= ((ulonglong) args[0]->max_length+
731
(ulonglong) args[3]->max_length);
732
if (max_result_length >= MAX_BLOB_WIDTH)
734
max_result_length= MAX_BLOB_WIDTH;
737
max_length= (ulong) max_result_length;
741
String *Item_str_conv::val_str(String *str)
745
if (!(res=args[0]->val_str(str)))
747
null_value=1; /* purecov: inspected */
748
return 0; /* purecov: inspected */
754
res= copy_if_not_alloced(str,res,res->length());
755
len= converter(collation.collation, (char*) res->ptr(), res->length(),
756
(char*) res->ptr(), res->length());
757
assert(len <= res->length());
762
uint len= res->length() * multiply;
763
tmp_value.alloc(len);
764
tmp_value.set_charset(collation.collation);
765
len= converter(collation.collation, (char*) res->ptr(), res->length(),
766
(char*) tmp_value.ptr(), len);
767
tmp_value.length(len);
774
void Item_func_lcase::fix_length_and_dec()
776
collation.set(args[0]->collation);
777
multiply= collation.collation->casedn_multiply;
778
converter= collation.collation->cset->casedn;
779
max_length= args[0]->max_length * multiply;
782
void Item_func_ucase::fix_length_and_dec()
784
collation.set(args[0]->collation);
785
multiply= collation.collation->caseup_multiply;
786
converter= collation.collation->cset->caseup;
787
max_length= args[0]->max_length * multiply;
791
String *Item_func_left::val_str(String *str)
794
String *res= args[0]->val_str(str);
796
/* must be longlong to avoid truncation */
797
longlong length= args[1]->val_int();
800
if ((null_value=(args[0]->null_value || args[1]->null_value)))
803
/* if "unsigned_flag" is set, we have a *huge* positive number. */
804
if ((length <= 0) && (!args[1]->unsigned_flag))
805
return &my_empty_string;
807
if ((res->length() <= (ulonglong) length) ||
808
(res->length() <= (char_pos= res->charpos((int) length))))
811
tmp_value.set(*res, 0, char_pos);
816
void Item_str_func::left_right_max_length()
818
max_length=args[0]->max_length;
819
if (args[1]->const_item())
821
int length=(int) args[1]->val_int()*collation.collation->mbmaxlen;
825
set_if_smaller(max_length,(uint) length);
830
void Item_func_left::fix_length_and_dec()
832
collation.set(args[0]->collation);
833
left_right_max_length();
837
String *Item_func_right::val_str(String *str)
840
String *res= args[0]->val_str(str);
841
/* must be longlong to avoid truncation */
842
longlong length= args[1]->val_int();
844
if ((null_value=(args[0]->null_value || args[1]->null_value)))
845
return 0; /* purecov: inspected */
847
/* if "unsigned_flag" is set, we have a *huge* positive number. */
848
if ((length <= 0) && (!args[1]->unsigned_flag))
849
return &my_empty_string; /* purecov: inspected */
851
if (res->length() <= (ulonglong) length)
852
return res; /* purecov: inspected */
854
uint start=res->numchars();
855
if (start <= (uint) length)
857
start=res->charpos(start - (uint) length);
858
tmp_value.set(*res,start,res->length()-start);
863
void Item_func_right::fix_length_and_dec()
865
collation.set(args[0]->collation);
866
left_right_max_length();
870
String *Item_func_substr::val_str(String *str)
873
String *res = args[0]->val_str(str);
874
/* must be longlong to avoid truncation */
875
longlong start= args[1]->val_int();
876
/* Assumes that the maximum length of a String is < INT_MAX32. */
877
/* Limit so that code sees out-of-bound value properly. */
878
longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
881
if ((null_value=(args[0]->null_value || args[1]->null_value ||
882
(arg_count == 3 && args[2]->null_value))))
883
return 0; /* purecov: inspected */
885
/* Negative or zero length, will return empty string. */
886
if ((arg_count == 3) && (length <= 0) &&
887
(length == 0 || !args[2]->unsigned_flag))
888
return &my_empty_string;
890
/* Assumes that the maximum length of a String is < INT_MAX32. */
891
/* Set here so that rest of code sees out-of-bound value as such. */
892
if ((length <= 0) || (length > INT_MAX32))
895
/* if "unsigned_flag" is set, we have a *huge* positive number. */
896
/* Assumes that the maximum length of a String is < INT_MAX32. */
897
if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
898
(args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
899
return &my_empty_string;
901
start= ((start < 0) ? res->numchars() + start : start - 1);
902
start= res->charpos((int) start);
903
if ((start < 0) || ((uint) start + 1 > res->length()))
904
return &my_empty_string;
906
length= res->charpos((int) length, (uint32) start);
907
tmp_length= res->length() - start;
908
length= min(length, tmp_length);
910
if (!start && (longlong) res->length() == length)
912
tmp_value.set(*res, (uint32) start, (uint32) length);
917
void Item_func_substr::fix_length_and_dec()
919
max_length=args[0]->max_length;
921
collation.set(args[0]->collation);
922
if (args[1]->const_item())
924
int32 start= (int32) args[1]->val_int();
926
max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start);
928
max_length-= min((uint)(start - 1), max_length);
930
if (arg_count == 3 && args[2]->const_item())
932
int32 length= (int32) args[2]->val_int();
934
max_length=0; /* purecov: inspected */
936
set_if_smaller(max_length,(uint) length);
938
max_length*= collation.collation->mbmaxlen;
942
void Item_func_substr_index::fix_length_and_dec()
944
max_length= args[0]->max_length;
946
if (agg_arg_charsets(collation, args, 2, MY_COLL_CMP_CONV, 1))
951
String *Item_func_substr_index::val_str(String *str)
954
String *res= args[0]->val_str(str);
955
String *delimiter= args[1]->val_str(&tmp_value);
956
int32 count= (int32) args[2]->val_int();
959
if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
960
{ // string and/or delim are null
965
uint delimiter_length= delimiter->length();
966
if (!res->length() || !delimiter_length || !count)
967
return &my_empty_string; // Wrong parameters
969
res->set_charset(collation.collation);
972
if (use_mb(res->charset()))
974
const char *ptr= res->ptr();
975
const char *strend= ptr+res->length();
976
const char *end= strend-delimiter_length+1;
977
const char *search= delimiter->ptr();
978
const char *search_end= search+delimiter_length;
979
int32 n=0,c=count,pass;
981
for (pass=(count>0);pass<2;++pass)
988
i=(char*) ptr+1; j=(char*) search+1;
989
while (j != search_end)
990
if (*i++ != *j++) goto skip;
992
else if (!--c) break;
993
ptr+= delimiter_length;
997
if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
999
} /* either not found or got total number when count<0 */
1000
if (pass == 0) /* count<0 */
1003
if (c<=0) return res; /* not found, return original string */
1008
if (c) return res; /* Not found, return original string */
1009
if (count>0) /* return left part */
1011
tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
1013
else /* return right part */
1015
ptr+= delimiter_length;
1016
tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
1025
{ // start counting from the beginning
1026
for (offset=0; ; offset+= delimiter_length)
1028
if ((int) (offset= res->strstr(*delimiter, offset)) < 0)
1029
return res; // Didn't find, return org string
1032
tmp_value.set(*res,0,offset);
1040
Negative index, start counting at the end
1042
for (offset=res->length(); offset ;)
1045
this call will result in finding the position pointing to one
1046
address space less than where the found substring is located
1049
if ((int) (offset= res->strrstr(*delimiter, offset)) < 0)
1050
return res; // Didn't find, return org string
1052
At this point, we've searched for the substring
1053
the number of times as supplied by the index value
1057
offset+= delimiter_length;
1058
tmp_value.set(*res,offset,res->length()- offset);
1065
We always mark tmp_value as const so that if val_str() is called again
1066
on this object, we don't disrupt the contents of tmp_value when it was
1067
derived from another String.
1069
tmp_value.mark_as_const();
1070
return (&tmp_value);
1074
** The trim functions are extension to ANSI SQL because they trim substrings
1075
** They ltrim() and rtrim() functions are optimized for 1 byte strings
1076
** They also return the original string if possible, else they return
1077
** a substring that points at the original string.
1081
String *Item_func_ltrim::val_str(String *str)
1084
char buff[MAX_FIELD_WIDTH], *ptr, *end;
1085
String tmp(buff,sizeof(buff),system_charset_info);
1086
String *res, *remove_str;
1089
res= args[0]->val_str(str);
1090
if ((null_value=args[0]->null_value))
1092
remove_str= &remove; /* Default value. */
1095
remove_str= args[1]->val_str(&tmp);
1096
if ((null_value= args[1]->null_value))
1100
if ((remove_length= remove_str->length()) == 0 ||
1101
remove_length > res->length())
1104
ptr= (char*) res->ptr();
1105
end= ptr+res->length();
1106
if (remove_length == 1)
1108
char chr=(*remove_str)[0];
1109
while (ptr != end && *ptr == chr)
1114
const char *r_ptr=remove_str->ptr();
1116
while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
1120
if (ptr == res->ptr())
1122
tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1127
String *Item_func_rtrim::val_str(String *str)
1130
char buff[MAX_FIELD_WIDTH], *ptr, *end;
1131
String tmp(buff, sizeof(buff), system_charset_info);
1132
String *res, *remove_str;
1135
res= args[0]->val_str(str);
1136
if ((null_value=args[0]->null_value))
1138
remove_str= &remove; /* Default value. */
1141
remove_str= args[1]->val_str(&tmp);
1142
if ((null_value= args[1]->null_value))
1146
if ((remove_length= remove_str->length()) == 0 ||
1147
remove_length > res->length())
1150
ptr= (char*) res->ptr();
1151
end= ptr+res->length();
1156
if (remove_length == 1)
1158
char chr=(*remove_str)[0];
1160
if (use_mb(res->charset()))
1164
if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr;
1170
while (ptr != end && end[-1] == chr)
1175
const char *r_ptr=remove_str->ptr();
1177
if (use_mb(res->charset()))
1180
while (ptr + remove_length < end)
1182
if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
1185
if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1195
while (ptr + remove_length <= end &&
1196
!memcmp(end-remove_length, r_ptr, remove_length))
1200
if (end == res->ptr()+res->length())
1202
tmp_value.set(*res,0,(uint) (end-res->ptr()));
1207
String *Item_func_trim::val_str(String *str)
1210
char buff[MAX_FIELD_WIDTH], *ptr, *end;
1212
String tmp(buff, sizeof(buff), system_charset_info);
1213
String *res, *remove_str;
1216
res= args[0]->val_str(str);
1217
if ((null_value=args[0]->null_value))
1219
remove_str= &remove; /* Default value. */
1222
remove_str= args[1]->val_str(&tmp);
1223
if ((null_value= args[1]->null_value))
1227
if ((remove_length= remove_str->length()) == 0 ||
1228
remove_length > res->length())
1231
ptr= (char*) res->ptr();
1232
end= ptr+res->length();
1233
r_ptr= remove_str->ptr();
1234
while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
1237
if (use_mb(res->charset()))
1242
while (ptr + remove_length < end)
1244
if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
1247
if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1258
while (ptr + remove_length <= end &&
1259
!memcmp(end-remove_length,r_ptr,remove_length))
1262
if (ptr == res->ptr() && end == ptr+res->length())
1264
tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1268
void Item_func_trim::fix_length_and_dec()
1270
max_length= args[0]->max_length;
1273
collation.set(args[0]->collation);
1274
remove.set_charset(collation.collation);
1275
remove.set_ascii(" ",1);
1279
// Handle character set for args[1] and args[0].
1280
// Note that we pass args[1] as the first item, and args[0] as the second.
1281
if (agg_arg_charsets(collation, &args[1], 2, MY_COLL_CMP_CONV, -1))
1286
void Item_func_trim::print(String *str, enum_query_type query_type)
1290
Item_func::print(str, query_type);
1293
str->append(Item_func_trim::func_name());
1295
str->append(mode_name());
1297
args[1]->print(str, query_type);
1298
str->append(STRING_WITH_LEN(" from "));
1299
args[0]->print(str, query_type);
1304
/* Item_func_password */
1306
String *Item_func_password::val_str(String *str)
1309
String *res= args[0]->val_str(str);
1310
if ((null_value=args[0]->null_value))
1312
if (res->length() == 0)
1313
return &my_empty_string;
1314
make_scrambled_password(tmp_value, res->c_ptr());
1315
str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, res->charset());
1319
char *Item_func_password::alloc(THD *thd, const char *password)
1321
char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH+1);
1323
make_scrambled_password(buff, password);
1327
#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
1329
String *Item_func_encrypt::val_str(String *str)
1332
String *res =args[0]->val_str(str);
1335
char salt[3],*salt_ptr;
1336
if ((null_value=args[0]->null_value))
1338
if (res->length() == 0)
1339
return &my_empty_string;
1342
{ // generate random salt
1343
time_t timestamp=current_thd->query_start();
1344
salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
1345
salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
1350
{ // obtain salt from the first two bytes
1351
String *salt_str=args[1]->val_str(&tmp_value);
1352
if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
1354
salt_ptr= salt_str->c_ptr();
1356
pthread_mutex_lock(&LOCK_crypt);
1357
char *tmp= crypt(res->c_ptr(),salt_ptr);
1360
pthread_mutex_unlock(&LOCK_crypt);
1364
str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
1366
pthread_mutex_unlock(&LOCK_crypt);
1371
#endif /* HAVE_CRYPT */
1374
void Item_func_encode::fix_length_and_dec()
1376
max_length=args[0]->max_length;
1377
maybe_null=args[0]->maybe_null || args[1]->maybe_null;
1378
collation.set(&my_charset_bin);
1381
String *Item_func_encode::val_str(String *str)
1385
String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
1389
if (!(res=args[0]->val_str(str)))
1391
null_value=1; /* purecov: inspected */
1392
return 0; /* purecov: inspected */
1395
if (!(password=args[1]->val_str(& tmp_pw_value)))
1402
res=copy_if_not_alloced(str,res,res->length());
1403
SQL_CRYPT sql_crypt(password->ptr());
1405
sql_crypt.encode((char*) res->ptr(),res->length());
1406
res->set_charset(&my_charset_bin);
1410
String *Item_func_decode::val_str(String *str)
1414
String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
1418
if (!(res=args[0]->val_str(str)))
1420
null_value=1; /* purecov: inspected */
1421
return 0; /* purecov: inspected */
1424
if (!(password=args[1]->val_str(& tmp_pw_value)))
1431
res=copy_if_not_alloced(str,res,res->length());
1432
SQL_CRYPT sql_crypt(password->ptr());
1434
sql_crypt.decode((char*) res->ptr(),res->length());
1439
Item *Item_func_sysconst::safe_charset_converter(CHARSET_INFO *tocs)
1443
String tmp, cstr, *ostr= val_str(&tmp);
1444
cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
1446
!(conv= new Item_static_string_func(fully_qualified_func_name(),
1447
cstr.ptr(), cstr.length(),
1449
collation.derivation)))
1453
conv->str_value.copy();
1454
conv->str_value.mark_as_const();
1459
String *Item_func_database::val_str(String *str)
1462
THD *thd= current_thd;
1463
if (thd->db == NULL)
1469
str->copy(thd->db, thd->db_length, system_charset_info);
1476
make USER() replicate properly (currently it is replicated to "")
1478
bool Item_func_user::init(const char *user, const char *host)
1482
// For system threads (e.g. replication SQL thread) user may be empty
1485
CHARSET_INFO *cs= str_value.charset();
1486
uint res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
1488
if (str_value.alloc(res_length))
1494
res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), res_length,
1495
"%s@%s", user, host);
1496
str_value.length(res_length);
1497
str_value.mark_as_const();
1503
bool Item_func_user::fix_fields(THD *thd, Item **ref)
1505
return (Item_func_sysconst::fix_fields(thd, ref) ||
1506
init(thd->main_security_ctx.user,
1507
thd->main_security_ctx.host_or_ip));
1511
bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
1513
if (Item_func_sysconst::fix_fields(thd, ref))
1516
Security_context *ctx=
1518
return init(ctx->priv_user, ctx->priv_host);
1523
Change a number to format '3,333,333,333.000'.
1525
This should be 'internationalized' sometimes.
1528
const int FORMAT_MAX_DECIMALS= 30;
1530
Item_func_format::Item_func_format(Item *org, Item *dec)
1531
: Item_str_func(org, dec)
1535
void Item_func_format::fix_length_and_dec()
1537
collation.set(default_charset());
1538
uint char_length= args[0]->max_length/args[0]->collation.collation->mbmaxlen;
1539
max_length= ((char_length + (char_length-args[0]->decimals)/3) *
1540
collation.collation->mbmaxlen);
1546
This needs to be fixed for multi-byte character set where numbers
1547
are stored in more than one byte
1550
String *Item_func_format::val_str(String *str)
1554
/* Number of decimal digits */
1556
/* Number of characters used to represent the decimals, including '.' */
1561
dec= (int) args[1]->val_int();
1562
if (args[1]->null_value)
1568
dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
1569
dec_length= dec ? dec+1 : 0;
1572
if (args[0]->result_type() == DECIMAL_RESULT ||
1573
args[0]->result_type() == INT_RESULT)
1575
my_decimal dec_val, rnd_dec, *res;
1576
res= args[0]->val_decimal(&dec_val);
1577
if ((null_value=args[0]->null_value))
1578
return 0; /* purecov: inspected */
1579
my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
1580
my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
1581
str_length= str->length();
1587
double nr= args[0]->val_real();
1588
if ((null_value=args[0]->null_value))
1589
return 0; /* purecov: inspected */
1590
nr= my_double_round(nr, (longlong) dec, false, false);
1591
/* Here default_charset() is right as this is not an automatic conversion */
1592
str->set_real(nr, dec, default_charset());
1595
str_length=str->length();
1597
str_length--; // Don't count sign
1599
/* We need this test to handle 'nan' values */
1600
if (str_length >= dec_length+4)
1603
length= str->length()+(diff=((int)(str_length- dec_length-1))/3);
1604
str= copy_if_not_alloced(&tmp_str,str,length);
1605
str->length(length);
1606
tmp= (char*) str->ptr()+length - dec_length-1;
1607
for (pos= (char*) str->ptr()+length-1; pos != tmp; pos--)
1611
*pos= *(pos - diff);
1613
*pos= *(pos - diff);
1615
*pos= *(pos - diff);
1626
void Item_func_format::print(String *str, enum_query_type query_type)
1628
str->append(STRING_WITH_LEN("format("));
1629
args[0]->print(str, query_type);
1631
args[1]->print(str, query_type);
1635
void Item_func_elt::fix_length_and_dec()
1640
if (agg_arg_charsets(collation, args+1, arg_count-1, MY_COLL_ALLOW_CONV, 1))
1643
for (uint i= 1 ; i < arg_count ; i++)
1645
set_if_bigger(max_length,args[i]->max_length);
1646
set_if_bigger(decimals,args[i]->decimals);
1648
maybe_null=1; // NULL if wrong first arg
1652
double Item_func_elt::val_real()
1657
if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
1659
double result= args[tmp]->val_real();
1660
null_value= args[tmp]->null_value;
1665
longlong Item_func_elt::val_int()
1670
if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
1673
longlong result= args[tmp]->val_int();
1674
null_value= args[tmp]->null_value;
1679
String *Item_func_elt::val_str(String *str)
1684
if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
1687
String *result= args[tmp]->val_str(str);
1689
result->set_charset(collation.collation);
1690
null_value= args[tmp]->null_value;
1695
void Item_func_make_set::split_sum_func(THD *thd, Item **ref_pointer_array,
1698
item->split_sum_func2(thd, ref_pointer_array, fields, &item, true);
1699
Item_str_func::split_sum_func(thd, ref_pointer_array, fields);
1703
void Item_func_make_set::fix_length_and_dec()
1705
max_length=arg_count-1;
1707
if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
1710
for (uint i=0 ; i < arg_count ; i++)
1711
max_length+=args[i]->max_length;
1713
used_tables_cache|= item->used_tables();
1714
not_null_tables_cache&= item->not_null_tables();
1715
const_item_cache&= item->const_item();
1716
with_sum_func= with_sum_func || item->with_sum_func;
1720
void Item_func_make_set::update_used_tables()
1722
Item_func::update_used_tables();
1723
item->update_used_tables();
1724
used_tables_cache|=item->used_tables();
1725
const_item_cache&=item->const_item();
1729
String *Item_func_make_set::val_str(String *str)
1735
String *result=&my_empty_string;
1737
bits=item->val_int();
1738
if ((null_value=item->null_value))
1742
bits &= ((ulonglong) 1 << arg_count)-1;
1744
for (; bits; bits >>= 1, ptr++)
1748
String *res= (*ptr)->val_str(str);
1749
if (res) // Skip nulls
1755
result=res; // Use original string
1758
if (tmp_str.copy(*res)) // Don't use 'str'
1759
return &my_empty_string;
1765
if (result != &tmp_str)
1766
{ // Copy data to tmp_str
1767
if (tmp_str.alloc(result->length()+res->length()+1) ||
1768
tmp_str.copy(*result))
1769
return &my_empty_string;
1772
if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
1773
return &my_empty_string;
1782
Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg)
1784
Item *new_item= item->transform(transformer, arg);
1789
THD::change_item_tree() should be called only if the tree was
1790
really transformed, i.e. when a new item has been created.
1791
Otherwise we'll be allocating a lot of unnecessary memory for
1792
change records at each execution.
1794
if (item != new_item)
1795
current_thd->change_item_tree(&item, new_item);
1796
return Item_str_func::transform(transformer, arg);
1800
void Item_func_make_set::print(String *str, enum_query_type query_type)
1802
str->append(STRING_WITH_LEN("make_set("));
1803
item->print(str, query_type);
1807
print_args(str, 0, query_type);
1813
String *Item_func_char::val_str(String *str)
1817
str->set_charset(collation.collation);
1818
for (uint i=0 ; i < arg_count ; i++)
1820
int32 num=(int32) args[i]->val_int();
1821
if (!args[i]->null_value)
1823
char char_num= (char) num;
1824
if (num&0xFF000000L) {
1825
str->append((char)(num>>24));
1827
} else if (num&0xFF0000L) {
1828
b2: str->append((char)(num>>16));
1830
} else if (num&0xFF00L) {
1831
b1: str->append((char)(num>>8));
1833
str->append(&char_num, 1);
1836
str->realloc(str->length()); // Add end 0 (for Purify)
1837
return check_well_formed_result(str);
1841
inline String* alloc_buffer(String *res,String *str,String *tmp_value,
1844
if (res->alloced_length() < length)
1846
if (str->alloced_length() >= length)
1848
(void) str->copy(*res);
1849
str->length(length);
1852
if (tmp_value->alloc(length))
1854
(void) tmp_value->copy(*res);
1855
tmp_value->length(length);
1858
res->length(length);
1863
void Item_func_repeat::fix_length_and_dec()
1865
collation.set(args[0]->collation);
1866
if (args[1]->const_item())
1868
/* must be longlong to avoid truncation */
1869
longlong count= args[1]->val_int();
1871
/* Assumes that the maximum length of a String is < INT_MAX32. */
1872
/* Set here so that rest of code sees out-of-bound value as such. */
1873
if (count > INT_MAX32)
1876
ulonglong max_result_length= (ulonglong) args[0]->max_length * count;
1877
if (max_result_length >= MAX_BLOB_WIDTH)
1879
max_result_length= MAX_BLOB_WIDTH;
1882
max_length= (ulong) max_result_length;
1886
max_length= MAX_BLOB_WIDTH;
1892
Item_func_repeat::str is carefully written to avoid reallocs
1893
as much as possible at the cost of a local buffer
1896
String *Item_func_repeat::val_str(String *str)
1899
uint length,tot_length;
1901
/* must be longlong to avoid truncation */
1902
longlong count= args[1]->val_int();
1903
String *res= args[0]->val_str(str);
1905
if (args[0]->null_value || args[1]->null_value)
1906
goto err; // string and/or delim are null
1909
if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
1910
return &my_empty_string;
1912
/* Assumes that the maximum length of a String is < INT_MAX32. */
1913
/* Bounds check on count: If this is triggered, we will error. */
1914
if ((ulonglong) count > INT_MAX32)
1916
if (count == 1) // To avoid reallocs
1918
length=res->length();
1919
// Safe length check
1920
if (length > current_thd->variables.max_allowed_packet / (uint) count)
1922
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
1923
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1924
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1925
func_name(), current_thd->variables.max_allowed_packet);
1928
tot_length= length*(uint) count;
1929
if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
1932
to=(char*) res->ptr()+length;
1935
memcpy(to,res->ptr(),length);
1946
void Item_func_rpad::fix_length_and_dec()
1948
// Handle character set for args[0] and args[2].
1949
if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
1951
if (args[1]->const_item())
1953
ulonglong length= 0;
1955
if (collation.collation->mbmaxlen > 0)
1957
ulonglong temp= (ulonglong) args[1]->val_int();
1959
/* Assumes that the maximum length of a String is < INT_MAX32. */
1960
/* Set here so that rest of code sees out-of-bound value as such. */
1961
if (temp > INT_MAX32)
1964
length= temp * collation.collation->mbmaxlen;
1967
if (length >= MAX_BLOB_WIDTH)
1969
length= MAX_BLOB_WIDTH;
1972
max_length= (ulong) length;
1976
max_length= MAX_BLOB_WIDTH;
1982
String *Item_func_rpad::val_str(String *str)
1985
uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
1987
const char *ptr_pad;
1988
/* must be longlong to avoid truncation */
1989
longlong count= args[1]->val_int();
1990
longlong byte_count;
1991
String *res= args[0]->val_str(str);
1992
String *rpad= args[2]->val_str(&rpad_str);
1994
if (!res || args[1]->null_value || !rpad ||
1995
((count < 0) && !args[1]->unsigned_flag))
1998
/* Assumes that the maximum length of a String is < INT_MAX32. */
1999
/* Set here so that rest of code sees out-of-bound value as such. */
2000
if ((ulonglong) count > INT_MAX32)
2002
if (count <= (res_char_length= res->numchars()))
2003
{ // String to pad is big enough
2004
res->length(res->charpos((int) count)); // Shorten result if longer
2007
pad_char_length= rpad->numchars();
2009
byte_count= count * collation.collation->mbmaxlen;
2010
if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2012
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2013
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2014
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2015
func_name(), current_thd->variables.max_allowed_packet);
2018
if (args[2]->null_value || !pad_char_length)
2020
res_byte_length= res->length(); /* Must be done before alloc_buffer */
2021
if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
2024
to= (char*) res->ptr()+res_byte_length;
2025
ptr_pad=rpad->ptr();
2026
pad_byte_length= rpad->length();
2027
count-= res_char_length;
2028
for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
2030
memcpy(to,ptr_pad,pad_byte_length);
2031
to+= pad_byte_length;
2035
pad_byte_length= rpad->charpos((int) count);
2036
memcpy(to,ptr_pad,(size_t) pad_byte_length);
2037
to+= pad_byte_length;
2039
res->length(to- (char*) res->ptr());
2048
void Item_func_lpad::fix_length_and_dec()
2050
// Handle character set for args[0] and args[2].
2051
if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
2054
if (args[1]->const_item())
2056
ulonglong length= 0;
2058
if (collation.collation->mbmaxlen > 0)
2060
ulonglong temp= (ulonglong) args[1]->val_int();
2062
/* Assumes that the maximum length of a String is < INT_MAX32. */
2063
/* Set here so that rest of code sees out-of-bound value as such. */
2064
if (temp > INT_MAX32)
2067
length= temp * collation.collation->mbmaxlen;
2070
if (length >= MAX_BLOB_WIDTH)
2072
length= MAX_BLOB_WIDTH;
2075
max_length= (ulong) length;
2079
max_length= MAX_BLOB_WIDTH;
2085
String *Item_func_lpad::val_str(String *str)
2088
uint32 res_char_length,pad_char_length;
2089
/* must be longlong to avoid truncation */
2090
longlong count= args[1]->val_int();
2091
longlong byte_count;
2092
String *res= args[0]->val_str(&tmp_value);
2093
String *pad= args[2]->val_str(&lpad_str);
2095
if (!res || args[1]->null_value || !pad ||
2096
((count < 0) && !args[1]->unsigned_flag))
2099
/* Assumes that the maximum length of a String is < INT_MAX32. */
2100
/* Set here so that rest of code sees out-of-bound value as such. */
2101
if ((ulonglong) count > INT_MAX32)
2104
res_char_length= res->numchars();
2106
if (count <= res_char_length)
2108
res->length(res->charpos((int) count));
2112
pad_char_length= pad->numchars();
2113
byte_count= count * collation.collation->mbmaxlen;
2115
if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2117
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2118
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2119
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2120
func_name(), current_thd->variables.max_allowed_packet);
2124
if (args[2]->null_value || !pad_char_length ||
2125
str->alloc((uint32) byte_count))
2129
str->set_charset(collation.collation);
2130
count-= res_char_length;
2131
while (count >= pad_char_length)
2134
count-= pad_char_length;
2137
str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
2149
String *Item_func_conv::val_str(String *str)
2152
String *res= args[0]->val_str(str);
2153
char *endptr,ans[65],*ptr;
2155
int from_base= (int) args[1]->val_int();
2156
int to_base= (int) args[2]->val_int();
2159
if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
2160
abs(to_base) > 36 || abs(to_base) < 2 ||
2161
abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
2167
unsigned_flag= !(from_base < 0);
2170
dec= my_strntoll(res->charset(), res->ptr(), res->length(),
2171
-from_base, &endptr, &err);
2173
dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
2174
from_base, &endptr, &err);
2176
ptr= longlong2str(dec, ans, to_base);
2177
if (str->copy(ans, (uint32) (ptr-ans), default_charset()))
2178
return &my_empty_string;
2183
String *Item_func_conv_charset::val_str(String *str)
2186
if (use_cached_value)
2187
return null_value ? 0 : &str_value;
2188
String *arg= args[0]->val_str(str);
2195
null_value= str_value.copy(arg->ptr(),arg->length(),arg->charset(),
2196
conv_charset, &dummy_errors);
2197
return null_value ? 0 : check_well_formed_result(&str_value);
2200
void Item_func_conv_charset::fix_length_and_dec()
2202
collation.set(conv_charset, DERIVATION_IMPLICIT);
2203
max_length = args[0]->max_length*conv_charset->mbmaxlen;
2206
void Item_func_conv_charset::print(String *str, enum_query_type query_type)
2208
str->append(STRING_WITH_LEN("convert("));
2209
args[0]->print(str, query_type);
2210
str->append(STRING_WITH_LEN(" using "));
2211
str->append(conv_charset->csname);
2215
String *Item_func_set_collation::val_str(String *str)
2218
str=args[0]->val_str(str);
2219
if ((null_value=args[0]->null_value))
2221
str->set_charset(collation.collation);
2225
void Item_func_set_collation::fix_length_and_dec()
2227
CHARSET_INFO *set_collation;
2228
const char *colname;
2229
String tmp, *str= args[1]->val_str(&tmp);
2230
colname= str->c_ptr();
2231
if (colname == binary_keyword)
2232
set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
2233
MY_CS_BINSORT,MYF(0));
2236
if (!(set_collation= get_charset_by_name(colname,MYF(0))))
2238
my_error(ER_UNKNOWN_COLLATION, MYF(0), colname);
2243
if (!set_collation ||
2244
!my_charset_same(args[0]->collation.collation,set_collation))
2246
my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
2247
colname, args[0]->collation.collation->csname);
2250
collation.set(set_collation, DERIVATION_EXPLICIT,
2251
args[0]->collation.repertoire);
2252
max_length= args[0]->max_length;
2256
bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
2258
/* Assume we don't have rtti */
2261
if (item->type() != FUNC_ITEM)
2263
Item_func *item_func=(Item_func*) item;
2264
if (arg_count != item_func->arg_count ||
2265
functype() != item_func->functype())
2267
Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
2268
if (collation.collation != item_func_sc->collation.collation)
2270
for (uint i=0; i < arg_count ; i++)
2271
if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
2277
void Item_func_set_collation::print(String *str, enum_query_type query_type)
2280
args[0]->print(str, query_type);
2281
str->append(STRING_WITH_LEN(" collate "));
2282
assert(args[1]->basic_const_item() &&
2283
args[1]->type() == Item::STRING_ITEM);
2284
args[1]->str_value.print(str);
2288
String *Item_func_charset::val_str(String *str)
2293
CHARSET_INFO *cs= args[0]->collation.collation;
2295
str->copy(cs->csname, strlen(cs->csname),
2296
&my_charset_latin1, collation.collation, &dummy_errors);
2300
String *Item_func_collation::val_str(String *str)
2304
CHARSET_INFO *cs= args[0]->collation.collation;
2307
str->copy(cs->name, strlen(cs->name),
2308
&my_charset_latin1, collation.collation, &dummy_errors);
2313
void Item_func_weight_string::fix_length_and_dec()
2315
CHARSET_INFO *cs= args[0]->collation.collation;
2316
collation.set(&my_charset_bin, args[0]->collation.derivation);
2317
flags= my_strxfrm_flag_normalize(flags, cs->levels_for_order);
2318
max_length= cs->mbmaxlen * max(args[0]->max_length, nweights);
2323
/* Return a weight_string according to collation */
2324
String *Item_func_weight_string::val_str(String *str)
2327
CHARSET_INFO *cs= args[0]->collation.collation;
2328
uint tmp_length, frm_length;
2331
if (args[0]->result_type() != STRING_RESULT ||
2332
!(res= args[0]->val_str(str)))
2335
tmp_length= cs->coll->strnxfrmlen(cs, cs->mbmaxlen *
2336
max(res->length(), nweights));
2338
if (tmp_value.alloc(tmp_length))
2341
frm_length= cs->coll->strnxfrm(cs,
2342
(uchar*) tmp_value.ptr(), tmp_length,
2343
nweights ? nweights : tmp_length,
2344
(const uchar*) res->ptr(), res->length(),
2346
tmp_value.length(frm_length);
2356
String *Item_func_hex::val_str(String *str)
2360
if (args[0]->result_type() != STRING_RESULT)
2364
/* Return hex of unsigned longlong value */
2365
if (args[0]->result_type() == REAL_RESULT ||
2366
args[0]->result_type() == DECIMAL_RESULT)
2368
double val= args[0]->val_real();
2369
if ((val <= (double) LONGLONG_MIN) ||
2370
(val >= (double) (ulonglong) ULONGLONG_MAX))
2373
dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
2376
dec= (ulonglong) args[0]->val_int();
2378
if ((null_value= args[0]->null_value))
2380
ptr= longlong2str(dec,ans,16);
2381
if (str->copy(ans,(uint32) (ptr-ans),default_charset()))
2382
return &my_empty_string; // End of memory
2386
/* Convert given string to a hex string, character by character */
2387
res= args[0]->val_str(str);
2388
if (!res || tmp_value.alloc(res->length()*2+1))
2394
tmp_value.length(res->length()*2);
2396
octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
2400
/** Convert given hex string to a binary string. */
2402
String *Item_func_unhex::val_str(String *str)
2404
const char *from, *end;
2410
res= args[0]->val_str(str);
2411
if (!res || tmp_value.alloc(length= (1+res->length())/2))
2419
tmp_value.length(length);
2420
to= (char*) tmp_value.ptr();
2421
if (res->length() % 2)
2424
*to++= hex_char= hexchar_to_int(*from++);
2425
if ((null_value= (hex_char == -1)))
2428
for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
2431
*to= (hex_char= hexchar_to_int(from[0])) << 4;
2432
if ((null_value= (hex_char == -1)))
2434
*to|= hex_char= hexchar_to_int(from[1]);
2435
if ((null_value= (hex_char == -1)))
2442
void Item_func_binary::print(String *str, enum_query_type query_type)
2444
str->append(STRING_WITH_LEN("cast("));
2445
args[0]->print(str, query_type);
2446
str->append(STRING_WITH_LEN(" as binary)"));
2452
String *Item_load_file::val_str(String *str)
2457
struct stat stat_info;
2458
char path[FN_REFLEN];
2460
if (!(file_name= args[0]->val_str(str)))
2463
(void) fn_format(path, file_name->c_ptr(), mysql_real_data_home, "",
2464
MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
2466
/* Read only allowed from within dir specified by secure_file_priv */
2467
if (opt_secure_file_priv &&
2468
strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv)))
2471
if (stat(path, &stat_info))
2474
if (!(stat_info.st_mode & S_IROTH))
2476
/* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
2479
if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
2481
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2482
ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2483
ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2484
func_name(), current_thd->variables.max_allowed_packet);
2487
if (tmp_value.alloc(stat_info.st_size))
2489
if ((file = my_open(file_name->c_ptr(), O_RDONLY, MYF(0))) < 0)
2491
if (my_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size, MYF(MY_NABP)))
2493
my_close(file, MYF(0));
2496
tmp_value.length(stat_info.st_size);
2497
my_close(file, MYF(0));
2507
String* Item_func_export_set::val_str(String* str)
2510
ulonglong the_set = (ulonglong) args[0]->val_int();
2511
String yes_buf, *yes;
2512
yes = args[1]->val_str(&yes_buf);
2514
no = args[2]->val_str(&no_buf);
2515
String *sep = NULL, sep_buf ;
2517
uint num_set_values = 64;
2518
ulonglong mask = 0x1;
2520
str->set_charset(collation.collation);
2522
/* Check if some argument is a NULL value */
2523
if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
2529
Arg count can only be 3, 4 or 5 here. This is guaranteed from the
2530
grammar for EXPORT_SET()
2534
num_set_values = (uint) args[4]->val_int();
2535
if (num_set_values > 64)
2537
if (args[4]->null_value)
2544
if (!(sep = args[3]->val_str(&sep_buf))) // Only true if NULL
2552
/* errors is not checked - assume "," can always be converted */
2554
sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin, collation.collation, &errors);
2559
assert(0); // cannot happen
2563
for (uint i = 0; i < num_set_values; i++, mask = (mask << 1))
2569
if (i != num_set_values - 1)
2575
void Item_func_export_set::fix_length_and_dec()
2577
uint length=max(args[1]->max_length,args[2]->max_length);
2578
uint sep_length=(arg_count > 3 ? args[3]->max_length : 1);
2579
max_length=length*64+sep_length*63;
2581
if (agg_arg_charsets(collation, args+1, min(4,arg_count)-1,
2582
MY_COLL_ALLOW_CONV, 1))
2587
#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))
2590
QUOTE() function returns argument string in single quotes suitable for
2591
using in a SQL statement.
2593
Adds a \\ before all characters that needs to be escaped in a SQL string.
2594
We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
2595
running commands from a file in windows.
2597
This function is very useful when you want to generate SQL statements.
2600
QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).
2608
String *Item_func_quote::val_str(String *str)
2612
Bit mask that has 1 for set for the position of the following characters:
2616
static uchar escmask[32]=
2618
0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
2619
0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
2620
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2621
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2624
char *from, *to, *end, *start;
2625
String *arg= args[0]->val_str(str);
2626
uint arg_length, new_length;
2627
if (!arg) // Null argument
2629
/* Return the string 'NULL' */
2630
str->copy(STRING_WITH_LEN("NULL"), collation.collation);
2635
arg_length= arg->length();
2636
new_length= arg_length+2; /* for beginning and ending ' signs */
2638
for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
2639
new_length+= get_esc_bit(escmask, (uchar) *from);
2641
if (tmp_value.alloc(new_length))
2645
We replace characters from the end to the beginning
2647
to= (char*) tmp_value.ptr() + new_length - 1;
2649
for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
2652
We can't use the bitmask here as we want to replace \O and ^Z with 0
2675
tmp_value.length(new_length);
2676
tmp_value.set_charset(collation.collation);
2685
longlong Item_func_uncompressed_length::val_int()
2688
String *res= args[0]->val_str(&value);
2692
return 0; /* purecov: inspected */
2695
if (res->is_empty()) return 0;
2698
res->ptr() using is safe because we have tested that string is not empty,
2699
res->c_ptr() is not used because:
2700
- we do not need \0 terminated string to get first 4 bytes
2701
- c_ptr() tests simbol after string end (uninitialiozed memory) which
2704
return uint4korr(res->ptr()) & 0x3FFFFFFF;
2707
longlong Item_func_crc32::val_int()
2710
String *res=args[0]->val_str(&value);
2714
return 0; /* purecov: inspected */
2717
return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
2720
#ifdef HAVE_COMPRESS
2723
String *Item_func_compress::val_str(String *str)
2725
int err= Z_OK, code;
2729
char *tmp, *last_char;
2732
if (!(res= args[0]->val_str(str)))
2738
if (res->is_empty()) return res;
2741
Citation from zlib.h (comment for compress function):
2743
Compresses the source buffer into the destination buffer. sourceLen is
2744
the byte length of the source buffer. Upon entry, destLen is the total
2745
size of the destination buffer, which must be at least 0.1% larger than
2746
sourceLen plus 12 bytes.
2747
We assume here that the buffer can't grow more than .25 %.
2749
new_size= res->length() + res->length() / 5 + 12;
2751
// Check new_size overflow: new_size <= res->length()
2752
if (((uint32) (new_size+5) <= res->length()) ||
2753
buffer.realloc((uint32) new_size + 4 + 1))
2759
body= ((Byte*)buffer.ptr()) + 4;
2761
// As far as we have checked res->is_empty() we can use ptr()
2762
if ((err= compress(body, &new_size,
2763
(const Bytef*)res->ptr(), res->length())) != Z_OK)
2765
code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
2766
push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
2771
tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
2772
int4store(tmp, res->length() & 0x3FFFFFFF);
2774
/* This is to ensure that things works for CHAR fields, which trim ' ': */
2775
last_char= ((char*)body)+new_size-1;
2776
if (*last_char == ' ')
2782
buffer.length((uint32)new_size + 4);
2787
String *Item_func_uncompress::val_str(String *str)
2790
String *res= args[0]->val_str(str);
2798
if (res->is_empty())
2801
/* If length is less than 4 bytes, data is corrupt */
2802
if (res->length() <= 4)
2804
push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
2805
ER_ZLIB_Z_DATA_ERROR,
2806
ER(ER_ZLIB_Z_DATA_ERROR));
2810
/* Size of uncompressed data is stored as first 4 bytes of field */
2811
new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
2812
if (new_size > current_thd->variables.max_allowed_packet)
2814
push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
2815
ER_TOO_BIG_FOR_UNCOMPRESS,
2816
ER(ER_TOO_BIG_FOR_UNCOMPRESS),
2817
current_thd->variables.max_allowed_packet);
2820
if (buffer.realloc((uint32)new_size))
2823
if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
2824
((const Bytef*)res->ptr())+4,res->length())) == Z_OK)
2826
buffer.length((uint32) new_size);
2830
code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
2831
((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
2832
push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
2842
DCE 1.1: Remote Procedure Call,
2843
Open Group Technical Standard Document Number C706, October 1997,
2844
(supersedes C309 DCE: Remote Procedure Call 8/1994,
2845
which was basis for ISO/IEC 11578:1996 specification)
2848
static struct rand_struct uuid_rand;
2849
static uint nanoseq;
2850
static ulonglong uuid_time=0;
2851
static char clock_seq_and_node_str[]="-0000-000000000000";
2854
number of 100-nanosecond intervals between
2855
1582-10-15 00:00:00.00 and 1970-01-01 00:00:00.00.
2857
#define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * 1000 * 10 )
2859
#define UUID_VERSION 0x1000
2860
#define UUID_VARIANT 0x8000
2862
static void tohex(char *to, uint from, uint len)
2867
*--to= _dig_vec_lower[from & 15];
2872
static void set_clock_seq_str()
2874
uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT;
2875
tohex(clock_seq_and_node_str+1, clock_seq, 4);
2879
String *Item_func_uuid::val_str(String *str)
2883
THD *thd= current_thd;
2885
pthread_mutex_lock(&LOCK_uuid_generator);
2886
if (! uuid_time) /* first UUID() call. initializing data */
2888
ulong tmp=sql_rnd_with_mutex();
2891
if (my_gethwaddr(mac))
2893
/* purecov: begin inspected */
2895
generating random "hardware addr"
2896
and because specs explicitly specify that it should NOT correlate
2897
with a clock_seq value (initialized random below), we use a separate
2900
randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)global_query_id);
2901
for (i=0; i < (int)sizeof(mac); i++)
2902
mac[i]=(uchar)(my_rnd(&uuid_rand)*255);
2905
s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1;
2906
for (i=sizeof(mac)-1 ; i>=0 ; i--)
2908
*--s=_dig_vec_lower[mac[i] & 15];
2909
*--s=_dig_vec_lower[mac[i] >> 4];
2911
randominit(&uuid_rand, tmp + (ulong) server_start_time,
2912
tmp + (ulong) thd->status_var.bytes_sent);
2913
set_clock_seq_str();
2916
ulonglong tv=my_getsystime() + UUID_TIME_OFFSET + nanoseq;
2917
if (unlikely(tv < uuid_time))
2918
set_clock_seq_str();
2919
else if (unlikely(tv == uuid_time))
2921
/* special protection from low-res system clocks */
2932
assert(tv > uuid_time);
2935
pthread_mutex_unlock(&LOCK_uuid_generator);
2937
uint32 time_low= (uint32) (tv & 0xFFFFFFFF);
2938
uint16 time_mid= (uint16) ((tv >> 32) & 0xFFFF);
2939
uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION);
2941
str->realloc(UUID_LENGTH+1);
2942
str->length(UUID_LENGTH);
2943
str->set_charset(system_charset_info);
2944
s=(char *) str->ptr();
2946
tohex(s, time_low, 8);
2947
tohex(s+9, time_mid, 4);
2948
tohex(s+14, time_hi_and_version, 4);
2949
strmov(s+18, clock_seq_and_node_str);