item_strfunc.cc 69.2 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
12

bk@work.mysql.com's avatar
bk@work.mysql.com committed
13 14 15 16 17 18 19
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/* This file defines all string functions
** Warning: Some string functions doesn't always put and end-null on a String
20
** (This shouldn't be needed)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
21 22 23 24 25 26 27 28 29 30 31 32
*/

#ifdef __GNUC__
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
#include "sql_acl.h"
#include <m_ctype.h>
#ifdef HAVE_CRYPT_H
#include <crypt.h>
#endif
33 34 35
#ifdef HAVE_OPENSSL
#include <openssl/des.h>
#endif /* HAVE_OPENSSL */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
36
#include "md5.h"
37 38
#include "sha1.h"
#include "my_aes.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
39

40
String empty_string("",default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
41 42 43 44 45 46

uint nr_of_decimals(const char *str)
{
  if ((str=strchr(str,'.')))
  {
    const char *start= ++str;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
47
    for (; my_isdigit(system_charset_info,*str) ; str++) ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
48 49 50 51 52 53 54
    return (uint) (str-start);
  }
  return 0;
}

double Item_str_func::val()
{
55
  int err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
56 57
  String *res;
  res=val_str(&str_value);
58
  return res ? my_strntod(res->charset(), (char*) res->ptr(),res->length(),
59
			  NULL, &err) : 0.0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
60 61 62 63
}

longlong Item_str_func::val_int()
{
64
  int err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
65 66
  String *res;
  res=val_str(&str_value);
67
  return res ? my_strntoll(res->charset(),res->ptr(),res->length(),10,NULL,&err) : (longlong) 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
68 69 70 71 72 73 74 75
}


String *Item_func_md5::val_str(String *str)
{
  String * sptr= args[0]->val_str(str);
  if (sptr)
  {
76
    my_MD5_CTX context;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
77 78 79
    unsigned char digest[16];

    null_value=0;
80 81 82
    my_MD5Init (&context);
    my_MD5Update (&context,(unsigned char *) sptr->ptr(), sptr->length());
    my_MD5Final (digest, &context);
83 84 85 86 87
    if (str->alloc(32))				// Ensure that memory is free
    {
      null_value=1;
      return 0;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    sprintf((char *) str->ptr(),
	    "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
	    digest[0], digest[1], digest[2], digest[3],
	    digest[4], digest[5], digest[6], digest[7],
	    digest[8], digest[9], digest[10], digest[11],
	    digest[12], digest[13], digest[14], digest[15]);
    str->length((uint) 32);
    return str;
  }
  null_value=1;
  return 0;
}


void Item_func_md5::fix_length_and_dec()
{
   max_length=32;
}

107 108 109 110 111 112 113

String *Item_func_sha::val_str(String *str)
{
  String * sptr= args[0]->val_str(str);
  if (sptr)  /* If we got value different from NULL */
  {
    SHA1_CONTEXT context;  /* Context used to generate SHA1 hash */
114
    /* Temporary buffer to store 160bit digest */
peter@linux.local's avatar
peter@linux.local committed
115
    uint8 digest[SHA1_HASH_SIZE];
116 117 118
    sha1_reset(&context);  /* We do not have to check for error here */
    /* No need to check error as the only case would be too long message */
    sha1_input(&context,(const unsigned char *) sptr->ptr(), sptr->length());
119
    /* Ensure that memory is free and we got result */
120
    if (!( str->alloc(SHA1_HASH_SIZE*2) || (sha1_result(&context,digest))))
121
    {
122 123
      sprintf((char *) str->ptr(),
      "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\
124 125 126 127 128 129
%02x%02x%02x%02x%02x%02x%02x%02x",
           digest[0], digest[1], digest[2], digest[3],
           digest[4], digest[5], digest[6], digest[7],
           digest[8], digest[9], digest[10], digest[11],
           digest[12], digest[13], digest[14], digest[15],
           digest[16], digest[17], digest[18], digest[19]);
130

131 132 133 134
      str->length((uint)  SHA1_HASH_SIZE*2);
      null_value=0;
      return str;
    }
135
  }
136 137 138 139 140 141 142 143
  null_value=1;
  return 0;
}

void Item_func_sha::fix_length_and_dec()
{
   max_length=SHA1_HASH_SIZE*2; // size of hex representation of hash
}
144 145 146 147


/* Implementation of AES encryption routines */

148 149
String *Item_func_aes_encrypt::val_str(String *str)
{
150
  char key_buff[80];
151
  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
152 153
  String *sptr= args[0]->val_str(str);			// String to encrypt
  String *key=  args[1]->val_str(&tmp_key_value);	// key
154 155 156 157
  int aes_length;
  if (sptr && key) // we need both arguments to be not NULL
  {
    null_value=0;
158
    aes_length=my_aes_get_size(sptr->length()); // Calculate result length
159

160
    if (!str_value.alloc(aes_length))		// Ensure that memory is free
161 162
    {
      // finally encrypt directly to allocated buffer.
163
      if (my_aes_encrypt(sptr->ptr(),sptr->length(), (char*) str_value.ptr(),
164
			 key->ptr(), key->length()) == aes_length)
165
      {
166
	// We got the expected result length
167 168
	str_value.length((uint) aes_length);
	return &str_value;
169 170 171 172 173 174 175
      }
    }
  }
  null_value=1;
  return 0;
}

176

177 178
void Item_func_aes_encrypt::fix_length_and_dec()
{
179
  max_length=my_aes_get_size(args[0]->max_length);
180 181 182 183 184
}


String *Item_func_aes_decrypt::val_str(String *str)
{
185
  char key_buff[80];
186 187
  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
  String *sptr, *key;
188 189 190 191 192
  DBUG_ENTER("Item_func_aes_decrypt::val_str");

  sptr= args[0]->val_str(str);			// String to decrypt
  key=  args[1]->val_str(&tmp_key_value);	// Key
  if (sptr && key)  			// Need to have both arguments not NULL
193 194
  {
    null_value=0;
195
    if (!str_value.alloc(sptr->length()))  // Ensure that memory is free
196
    {
197
      // finally decrypt directly to allocated buffer.
198 199 200
      int length;
      length=my_aes_decrypt(sptr->ptr(), sptr->length(),
			    (char*) str_value.ptr(),
201 202
                            key->ptr(), key->length());
      if (length >= 0)  // if we got correct data data
203
      {
204 205
        str_value.length((uint) length);
        DBUG_RETURN(&str_value);
206
      }
207 208 209 210
    }
  }
  // Bad parameters. No memory or bad data will all go here
  null_value=1;
211
  DBUG_RETURN(0);
212 213
}

214

215 216 217 218
void Item_func_aes_decrypt::fix_length_and_dec()
{
   max_length=args[0]->max_length;
}
219 220


bk@work.mysql.com's avatar
bk@work.mysql.com committed
221
/*
222 223 224
  Concatenate args with the following premises:
  If only one arg (which is ok), return value of arg
  Don't reallocate val_str() if not absolute necessary.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
225 226 227 228 229 230 231 232 233 234 235 236 237
*/

String *Item_func_concat::val_str(String *str)
{
  String *res,*res2,*use_as_buff;
  uint i;

  null_value=0;
  if (!(res=args[0]->val_str(str)))
    goto null;
  use_as_buff= &tmp_value;
  for (i=1 ; i < arg_count ; i++)
  {
238
    if (args[i]->binary())
239
      set_charset(&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
240 241 242 243 244 245 246 247 248 249 250
    if (res->length() == 0)
    {
      if (!(res=args[i]->val_str(str)))
	goto null;
    }
    else
    {
      if (!(res2=args[i]->val_str(use_as_buff)))
	goto null;
      if (res2->length() == 0)
	continue;
251 252
      if (res->length()+res2->length() >
	  current_thd->variables.max_allowed_packet)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	goto null;				// Error check
      if (res->alloced_length() >= res->length()+res2->length())
      {						// Use old buffer
	res->append(*res2);
      }
      else if (str->alloced_length() >= res->length()+res2->length())
      {
	if (str == res2)
	  str->replace(0,0,*res);
	else
	{
	  str->copy(*res);
	  str->append(*res2);
	}
	res=str;
268
	res->set_charset(charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
269 270 271 272 273 274 275 276 277 278 279
      }
      else if (res == &tmp_value)
      {
	if (res->append(*res2))			// Must be a blob
	  goto null;
      }
      else if (res2 == &tmp_value)
      {						// This can happend only 1 time
	if (tmp_value.replace(0,0,*res))
	  goto null;
	res= &tmp_value;
280
	res->set_charset(charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	use_as_buff=str;			// Put next arg here
      }
      else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
	       res2->ptr() <= tmp_value.ptr() + tmp_value.alloced_length())
      {
	/*
	  This happens really seldom:
	  In this case res2 is sub string of tmp_value.  We will
	  now work in place in tmp_value to set it to res | res2
	*/
	/* Chop the last characters in tmp_value that isn't in res2 */
	tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
			 res2->length());
	/* Place res2 at start of tmp_value, remove chars before res2 */
	if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
			      *res))
	  goto null;
	res= &tmp_value;
299
	res->set_charset(charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
300 301 302 303 304 305 306 307 308
	use_as_buff=str;			// Put next arg here
      }
      else
      {						// Two big const strings
	if (tmp_value.alloc(max_length) ||
	    tmp_value.copy(*res) ||
	    tmp_value.append(*res2))
	  goto null;
	res= &tmp_value;
309
	res->set_charset(charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	use_as_buff=str;
      }
    }
  }
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_concat::fix_length_and_dec()
{
  max_length=0;
  for (uint i=0 ; i < arg_count ; i++)
    max_length+=args[i]->max_length;
  if (max_length > MAX_BLOB_WIDTH)
  {
    max_length=MAX_BLOB_WIDTH;
    maybe_null=1;
  }
}

334
/*
335 336
  Function des_encrypt() by tonu@spam.ee & monty
  Works only if compiled with OpenSSL library support.
337
  This returns a binary string where first character is CHAR(128 | key-number).
338
  If one uses a string key key_number is 127.
339
  Encryption result is longer than original by formula:
340
  new_length= org_length + (8-(org_length % 8))+1
341 342
*/

343 344 345
String *Item_func_des_encrypt::val_str(String *str)
{
#ifdef HAVE_OPENSSL
346
  des_cblock ivec;
347 348
  struct st_des_keyblock keyblock;
  struct st_des_keyschedule keyschedule;
349 350
  const char *append_str="********";
  uint key_number, res_length, tail;
351
  String *res= args[0]->val_str(str);
352 353 354

  if ((null_value=args[0]->null_value))
    return 0;
355
  if ((res_length=res->length()) == 0)
356
    return &empty_string;
357

358
  if (arg_count == 1)
359 360 361 362 363 364
  {
    /* Protect against someone doing FLUSH DES_KEY_FILE */
    VOID(pthread_mutex_lock(&LOCK_des_key_file));
    keyschedule= des_keyschedule[key_number=des_default_key];
    VOID(pthread_mutex_unlock(&LOCK_des_key_file));
  }
365
  else if (args[1]->result_type() == INT_RESULT)
366 367 368 369
  {
    key_number= (uint) args[1]->val_int();
    if (key_number > 9)
      goto error;
370 371 372
    VOID(pthread_mutex_lock(&LOCK_des_key_file));
    keyschedule= des_keyschedule[key_number];
    VOID(pthread_mutex_unlock(&LOCK_des_key_file));
373
  }
374 375 376 377 378
  else
  {
    String *keystr=args[1]->val_str(&tmp_value);
    if (!keystr)
      goto error;
379
    key_number=127;				// User key string
380 381

    /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */
382
    bzero((char*) &ivec,sizeof(ivec));
383 384 385
    EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
		   (uchar*) keystr->ptr(), (int) keystr->length(),
		   1, (uchar*) &keyblock,ivec);
386 387 388
    des_set_key_unchecked(&keyblock.key1,keyschedule.ks1);
    des_set_key_unchecked(&keyblock.key2,keyschedule.ks2);
    des_set_key_unchecked(&keyblock.key3,keyschedule.ks3);
389 390
  }

391
  /*
392
     The problem: DES algorithm requires original data to be in 8-bytes
393 394
     chunks. Missing bytes get filled with '*'s and result of encryption
     can be up to 8 bytes longer than original string. When decrypted,
395
     we do not know the size of original string :(
396 397
     We add one byte with value 0x1..0x8 as the last byte of the padded
     string marking change of string length.
398 399
  */

400 401 402
  tail=  (8-(res_length) % 8);			// 1..8 marking extra length
  res_length+=tail;
  if (tail && res->append(append_str, tail) || tmp_value.alloc(res_length+1))
403
    goto error;
404 405 406
  (*res)[res_length-1]=tail;			// save extra length
  tmp_value.length(res_length+1);
  tmp_value[0]=(char) (128 | key_number);
407
  // Real encryption
408
  bzero((char*) &ivec,sizeof(ivec));
409
  des_ede3_cbc_encrypt((const uchar*) (res->ptr()),
410
		       (uchar*) (tmp_value.ptr()+1),
411 412 413 414
		       res_length,
		       keyschedule.ks1,
		       keyschedule.ks2,
		       keyschedule.ks3,
415 416 417 418 419
		       &ivec, TRUE);
  return &tmp_value;

error:
#endif	/* HAVE_OPENSSL */
420 421 422 423
  null_value=1;
  return 0;
}

424

425 426 427 428
String *Item_func_des_decrypt::val_str(String *str)
{
#ifdef HAVE_OPENSSL
  des_key_schedule ks1, ks2, ks3;
429
  des_cblock ivec;
430 431
  struct st_des_keyblock keyblock;
  struct st_des_keyschedule keyschedule;
432
  String *res= args[0]->val_str(str);
433
  uint length=res->length(),tail;
434 435 436

  if ((null_value=args[0]->null_value))
    return 0;
437 438
  length=res->length();
  if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128))
439
    return res;				// Skip decryption if not encrypted
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
440

441
  if (arg_count == 1)			// If automatic uncompression
442
  {
443
    uint key_number=(uint) (*res)[0] & 127;
444
    // Check if automatic key and that we have privilege to uncompress using it
445
    if (!(current_thd->master_access & SUPER_ACL) || key_number > 9)
446
      goto error;
447 448 449
    VOID(pthread_mutex_lock(&LOCK_des_key_file));
    keyschedule= des_keyschedule[key_number];
    VOID(pthread_mutex_unlock(&LOCK_des_key_file));
450
  }
451 452 453 454
  else
  {
    // We make good 24-byte (168 bit) key from given plaintext key with MD5
    String *keystr=args[1]->val_str(&tmp_value);
455
    if (!keystr)
456
      goto error;
457

458
    bzero((char*) &ivec,sizeof(ivec));
459 460 461 462
    EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
		   (uchar*) keystr->ptr(),(int) keystr->length(),
		   1,(uchar*) &keyblock,ivec);
    // Here we set all 64-bit keys (56 effective) one by one
463 464
    des_set_key_unchecked(&keyblock.key1,keyschedule.ks1);
    des_set_key_unchecked(&keyblock.key2,keyschedule.ks2);
465
    des_set_key_unchecked(&keyblock.key3,keyschedule.ks3);
466
  }
467
  if (tmp_value.alloc(length-1))
468
    goto error;
469 470

  bzero((char*) &ivec,sizeof(ivec));
471
  des_ede3_cbc_encrypt((const uchar*) res->ptr()+1,
472
		       (uchar*) (tmp_value.ptr()),
473 474 475 476
		       length-1,
		       keyschedule.ks1,
		       keyschedule.ks2,
		       keyschedule.ks3,
477
		       &ivec, FALSE);
478 479 480 481
  /* Restore old length of key */
  if ((tail=(uint) (uchar) tmp_value[length-2]) > 8)
    goto error;					// Wrong key
  tmp_value.length(length-1-tail);
482 483 484 485
  return &tmp_value;

error:
#endif	/* HAVE_OPENSSL */
486 487 488 489 490
  null_value=1;
  return 0;
}


491
/*
492 493
  concat with separator. First arg is the separator
  concat_ws takes at least two arguments.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
494 495 496 497 498
*/

String *Item_func_concat_ws::val_str(String *str)
{
  char tmp_str_buff[10];
499
  String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
500 501 502 503 504 505 506 507
         *sep_str, *res, *res2,*use_as_buff;
  uint i;

  null_value=0;
  if (!(sep_str= separator->val_str(&tmp_sep_str)))
    goto null;

  use_as_buff= &tmp_value;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
508
  str->length(0);				// QQ; Should be removed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
509 510 511 512
  res=str;

  // Skip until non-null and non-empty argument is found.
  // If not, return the empty string
513 514 515
  for (i=0; i < arg_count; i++)
    if ((res= args[i]->val_str(str)) && res->length())
      break;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
516 517
  if (i ==  arg_count)
    return &empty_string;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
518 519 520 521

  for (i++; i < arg_count ; i++)
  {
    if (!(res2= args[i]->val_str(use_as_buff)) || !res2->length())
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
522
      continue;					// Skip NULL and empty string
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
523 524

    if (res->length() + sep_str->length() + res2->length() >
525
	current_thd->variables.max_allowed_packet)
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
526 527 528 529 530 531 532 533 534
      goto null;				// Error check
    if (res->alloced_length() >=
	res->length() + sep_str->length() + res2->length())
    {						// Use old buffer
      res->append(*sep_str);			// res->length() > 0 always
      res->append(*res2);
    }
    else if (str->alloced_length() >=
	     res->length() + sep_str->length() + res2->length())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
535
    {
536 537 538 539 540 541 542 543 544 545 546 547
      /* We have room in str;  We can't get any errors here */
      if (str == res2)
      {						// This is quote uncommon!
	str->replace(0,0,*sep_str);
	str->replace(0,0,*res);
      }
      else
      {
	str->copy(*res);
	str->append(*sep_str);
	str->append(*res2);
      }
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
548 549 550 551 552
      res=str;
      use_as_buff= &tmp_value;
    }
    else if (res == &tmp_value)
    {
553
      if (res->append(*sep_str) || res->append(*res2))
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
554 555
	goto null; // Must be a blob
    }
556 557 558 559 560 561 562
    else if (res2 == &tmp_value)
    {						// This can happend only 1 time
      if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res))
	goto null;
      res= &tmp_value;
      use_as_buff=str;				// Put next arg here
    }
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
563
    else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
564
	     res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
565 566 567 568
    {
      /*
	This happens really seldom:
	In this case res2 is sub string of tmp_value.  We will
569
	now work in place in tmp_value to set it to res | sep_str | res2
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
570 571 572 573 574 575
      */
      /* Chop the last characters in tmp_value that isn't in res2 */
      tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
		       res2->length());
      /* Place res2 at start of tmp_value, remove chars before res2 */
      if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
576 577
			    *res) ||
	  tmp_value.replace(res->length(),0, *sep_str))
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
578 579 580 581 582 583 584 585 586 587 588 589 590
	goto null;
      res= &tmp_value;
      use_as_buff=str;			// Put next arg here
    }
    else
    {						// Two big const strings
      if (tmp_value.alloc(max_length) ||
	  tmp_value.copy(*res) ||
	  tmp_value.append(*sep_str) ||
	  tmp_value.append(*res2))
	goto null;
      res= &tmp_value;
      use_as_buff=str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
591 592 593 594 595 596 597 598 599
    }
  }
  return res;

null:
  null_value=1;
  return 0;
}

600 601
void Item_func_concat_ws::split_sum_func(Item **ref_pointer_array,
					 List<Item> &fields)
602 603
{
  if (separator->with_sum_func && separator->type() != SUM_FUNC_ITEM)
604
    separator->split_sum_func(ref_pointer_array, fields);
605 606
  else if (separator->used_tables() || separator->type() == SUM_FUNC_ITEM)
  {
607
    uint el= fields.elements;
608
    fields.push_front(separator);
609 610 611 612
    ref_pointer_array[el]= separator;
    separator= new Item_ref(ref_pointer_array + el, 0, separator->name);
  }
  Item_str_func::split_sum_func(ref_pointer_array, fields);
613
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
614 615 616

void Item_func_concat_ws::fix_length_and_dec()
{
617
  max_length=separator->max_length*(arg_count-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
618 619 620 621 622 623 624
  for (uint i=0 ; i < arg_count ; i++)
    max_length+=args[i]->max_length;
  if (max_length > MAX_BLOB_WIDTH)
  {
    max_length=MAX_BLOB_WIDTH;
    maybe_null=1;
  }
625 626
  used_tables_cache|=separator->used_tables();
  const_item_cache&=separator->const_item();
627
  with_sum_func= with_sum_func || separator->with_sum_func;
628 629 630 631 632 633 634 635
}

void Item_func_concat_ws::update_used_tables()
{
  Item_func::update_used_tables();
  separator->update_used_tables();
  used_tables_cache|=separator->used_tables();
  const_item_cache&=separator->const_item();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
}


String *Item_func_reverse::val_str(String *str)
{
  String *res = args[0]->val_str(str);
  char *ptr,*end;

  if ((null_value=args[0]->null_value))
    return 0;
  /* An empty string is a special case as the string pointer may be null */
  if (!res->length())
    return &empty_string;
  res=copy_if_not_alloced(str,res,res->length());
  ptr = (char *) res->ptr();
  end=ptr+res->length();
#ifdef USE_MB
653
  if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
654 655 656 657 658 659 660
  {
    String tmpstr;
    tmpstr.copy(*res);
    char *tmp = (char *) tmpstr.ptr() + tmpstr.length();
    register uint32 l;
    while (ptr < end)
    {
661
      if ((l=my_ismbchar(res->charset(), ptr,end)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
        tmp-=l, memcpy(tmp,ptr,l), ptr+=l;
      else
        *--tmp=*ptr++;
    }
    memcpy((char *) res->ptr(),(char *) tmpstr.ptr(), res->length());
  }
  else
#endif /* USE_MB */
  {
    char tmp;
    while (ptr < end)
    {
      tmp=*ptr;
      *ptr++=*--end;
      *end=tmp;
    }
  }
  return res;
}


void Item_func_reverse::fix_length_and_dec()
{
  max_length = args[0]->max_length;
}

/*
** Replace all occurences of string2 in string1 with string3.
690
** Don't reallocate val_str() if not needed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
691 692 693 694 695 696 697
*/

/* TODO: Fix that this works with binary strings when using USE_MB */

String *Item_func_replace::val_str(String *str)
{
  String *res,*res2,*res3;
698
  int offset;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
699 700 701 702 703
  uint from_length,to_length;
  bool alloced=0;
#ifdef USE_MB
  const char *ptr,*end,*strend,*search,*search_end;
  register uint32 l;
704
  bool binary_cmp;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
705 706 707 708 709 710 711 712 713 714
#endif

  null_value=0;
  res=args[0]->val_str(str);
  if (args[0]->null_value)
    goto null;
  res2=args[1]->val_str(&tmp_value);
  if (args[1]->null_value)
    goto null;

715
#ifdef USE_MB
716
  binary_cmp = (args[0]->binary() || args[1]->binary() || !use_mb(res->charset()));
717 718
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
719 720 721 722 723 724
  if (res2->length() == 0)
    return res;
#ifndef USE_MB
  if ((offset=res->strstr(*res2)) < 0)
    return res;
#else
725
  offset=0;
726
  if (binary_cmp && (offset=res->strstr(*res2)) < 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
727 728 729 730 731 732 733 734
    return res;
#endif
  if (!(res3=args[2]->val_str(&tmp_value2)))
    goto null;
  from_length= res2->length();
  to_length=   res3->length();

#ifdef USE_MB
735
  if (!binary_cmp)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
  {
    search=res2->ptr();
    search_end=search+from_length;
redo:
    ptr=res->ptr()+offset;
    strend=res->ptr()+res->length();
    end=strend-from_length+1;
    while (ptr < end)
    {
        if (*ptr == *search)
        {
          register char *i,*j;
          i=(char*) ptr+1; j=(char*) search+1;
          while (j != search_end)
            if (*i++ != *j++) goto skipp;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
751
          offset= (int) (ptr-res->ptr());
752 753
          if (res->length()-from_length + to_length >
	      current_thd->variables.max_allowed_packet)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
754 755 756 757 758 759 760
            goto null;
          if (!alloced)
          {
            alloced=1;
            res=copy_if_not_alloced(str,res,res->length()+to_length);
          }
          res->replace((uint) offset,from_length,*res3);
761
	  offset+=(int) to_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
762 763 764
          goto redo;
        }
skipp:
765
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
766 767 768 769 770 771 772
        else ++ptr;
    }
  }
  else
#endif /* USE_MB */
    do
    {
773 774
      if (res->length()-from_length + to_length >
	  current_thd->variables.max_allowed_packet)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
775 776 777 778 779 780 781 782 783
        goto null;
      if (!alloced)
      {
        alloced=1;
        res=copy_if_not_alloced(str,res,res->length()+to_length);
      }
      res->replace((uint) offset,from_length,*res3);
      offset+=(int) to_length;
    }
784
    while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_replace::fix_length_and_dec()
{
  max_length=args[0]->max_length;
  int diff=(int) (args[2]->max_length - args[1]->max_length);
  if (diff > 0 && args[1]->max_length)
  {						// Calculate of maxreplaces
    max_length= max_length/args[1]->max_length;
    max_length= (max_length+1)*(uint) diff;
  }
  if (max_length > MAX_BLOB_WIDTH)
  {
    max_length=MAX_BLOB_WIDTH;
    maybe_null=1;
  }
}


String *Item_func_insert::val_str(String *str)
{
  String *res,*res2;
  uint start,length;

  null_value=0;
  res=args[0]->val_str(str);
  res2=args[3]->val_str(&tmp_value);
  start=(uint) args[1]->val_int()-1;
  length=(uint) args[2]->val_int();
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
      args[3]->null_value)
    goto null; /* purecov: inspected */
823 824
  start=res->charpos(start);
  length=res->charpos(length,start);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
825
  if (start > res->length()+1)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
826
    return res;					// Wrong param; skip insert
bk@work.mysql.com's avatar
bk@work.mysql.com committed
827 828
  if (length > res->length()-start)
    length=res->length()-start;
829 830
  if (res->length() - length + res2->length() >
      current_thd->variables.max_allowed_packet)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    goto null;					// OOM check
  res=copy_if_not_alloced(str,res,res->length());
  res->replace(start,length,*res2);
  return res;
null:
  null_value=1;
  return 0;
}


void Item_func_insert::fix_length_and_dec()
{
  max_length=args[0]->max_length+args[3]->max_length;
  if (max_length > MAX_BLOB_WIDTH)
  {
    max_length=MAX_BLOB_WIDTH;
    maybe_null=1;
  }
}


String *Item_func_lcase::val_str(String *str)
{
  String *res;
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  null_value=0;
  res=copy_if_not_alloced(str,res,res->length());
  res->casedn();
  return res;
}


String *Item_func_ucase::val_str(String *str)
{
  String *res;
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  null_value=0;
  res=copy_if_not_alloced(str,res,res->length());
  res->caseup();
  return res;
}


String *Item_func_left::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  long length  =(long) args[1]->val_int();

  if ((null_value=args[0]->null_value))
    return 0;
  if (length <= 0)
    return &empty_string;
891
  length= res->charpos(length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
892 893 894 895 896
  if (res->length() > (ulong) length)
  {						// Safe even if const arg
    if (!res->alloced_length())
    {						// Don't change const str
      str_value= *res;				// Not malloced string
897
      set_charset(res->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
      res= &str_value;
    }
    res->length((uint) length);
  }
  return res;
}


void Item_str_func::left_right_max_length()
{
  max_length=args[0]->max_length;
  if (args[1]->const_item())
  {
    int length=(int) args[1]->val_int();
    if (length <= 0)
      max_length=0;
    else
      set_if_smaller(max_length,(uint) length);
  }
}


void Item_func_left::fix_length_and_dec()
{
  left_right_max_length();
}


String *Item_func_right::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  long length  =(long) args[1]->val_int();

  if ((null_value=args[0]->null_value))
    return 0; /* purecov: inspected */
  if (length <= 0)
    return &empty_string; /* purecov: inspected */
  if (res->length() <= (uint) length)
    return res; /* purecov: inspected */
937 938 939 940 941

  uint start=res->numchars()-(uint) length;
  if (start<=0) return res;
  start=res->charpos(start);
  tmp_value.set(*res,start,res->length()-start);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
  return &tmp_value;
}


void Item_func_right::fix_length_and_dec()
{
  left_right_max_length();
}


String *Item_func_substr::val_str(String *str)
{
  String *res  = args[0]->val_str(str);
  int32 start	= (int32) args[1]->val_int()-1;
  int32 length	= arg_count == 3 ? (int32) args[2]->val_int() : INT_MAX32;
  int32 tmp_length;

  if ((null_value=(args[0]->null_value || args[1]->null_value ||
		   (arg_count == 3 && args[2]->null_value))))
    return 0; /* purecov: inspected */
962 963
  start=res->charpos(start);
  length=res->charpos(length,start);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
  if (start < 0 || (uint) start+1 > res->length() || length <= 0)
    return &empty_string;

  tmp_length=(int32) res->length()-start;
  length=min(length,tmp_length);

  if (!start && res->length() == (uint) length)
    return res;
  tmp_value.set(*res,(uint) start,(uint) length);
  return &tmp_value;
}


void Item_func_substr::fix_length_and_dec()
{
  max_length=args[0]->max_length;

  if (args[1]->const_item())
  {
    int32 start=(int32) args[1]->val_int()-1;
    if (start < 0 || start >= (int32) max_length)
      max_length=0; /* purecov: inspected */
    else
      max_length-= (uint) start;
  }
  if (arg_count == 3 && args[2]->const_item())
  {
    int32 length= (int32) args[2]->val_int();
    if (length <= 0)
      max_length=0; /* purecov: inspected */
    else
      set_if_smaller(max_length,(uint) length);
  }
}


String *Item_func_substr_index::val_str(String *str)
{
  String *res =args[0]->val_str(str);
  String *delimeter =args[1]->val_str(&tmp_value);
  int32 count = (int32) args[2]->val_int();
  uint offset;

  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
  {					// string and/or delim are null
    null_value=1;
    return 0;
  }
  null_value=0;
  uint delimeter_length=delimeter->length();
  if (!res->length() || !delimeter_length || !count)
    return &empty_string;		// Wrong parameters

#ifdef USE_MB
1018
  if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  {
    const char *ptr=res->ptr();
    const char *strend = ptr+res->length();
    const char *end=strend-delimeter_length+1;
    const char *search=delimeter->ptr();
    const char *search_end=search+delimeter_length;
    int32 n=0,c=count,pass;
    register uint32 l;
    for (pass=(count>0);pass<2;++pass)
    {
      while (ptr < end)
      {
        if (*ptr == *search)
        {
	  register char *i,*j;
	  i=(char*) ptr+1; j=(char*) search+1;
	  while (j != search_end)
	    if (*i++ != *j++) goto skipp;
	  if (pass==0) ++n;
	  else if (!--c) break;
	  ptr+=delimeter_length;
	  continue;
	}
    skipp:
1043
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
        else ++ptr;
      } /* either not found or got total number when count<0 */
      if (pass == 0) /* count<0 */
      {
        c+=n+1;
        if (c<=0) return res; /* not found, return original string */
        ptr=res->ptr();
      }
      else
      {
        if (c) return res; /* Not found, return original string */
        if (count>0) /* return left part */
        {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1057
	  tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1058 1059 1060 1061
        }
        else /* return right part */
        {
	  ptr+=delimeter_length;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1062
	  tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        }
      }
    }
  }
  else
#endif /* USE_MB */
  {
    if (count > 0)
    {					// start counting from the beginning
      for (offset=0 ;; offset+=delimeter_length)
      {
	if ((int) (offset=res->strstr(*delimeter,offset)) < 0)
	  return res;			// Didn't find, return org string
	if (!--count)
	{
	  tmp_value.set(*res,0,offset);
	  break;
	}
      }
    }
    else
    {					// Start counting at end
1085
      for (offset=res->length() ; ; offset-=delimeter_length-1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
      {
	if ((int) (offset=res->strrstr(*delimeter,offset)) < 0)
	  return res;			// Didn't find, return org string
	if (!++count)
	{
	  offset+=delimeter_length;
	  tmp_value.set(*res,offset,res->length()- offset);
	  break;
	}
      }
    }
  }
  return (&tmp_value);
}

/*
** The trim functions are extension to ANSI SQL because they trim substrings
** They ltrim() and rtrim() functions are optimized for 1 byte strings
** They also return the original string if possible, else they return
** a substring that points at the original string.
*/


String *Item_func_ltrim::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;					/* purecov: inspected */
  char buff[MAX_FIELD_WIDTH];
1115
  String tmp(buff,sizeof(buff),res->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
  String *remove_str=args[1]->val_str(&tmp);
  uint remove_length;
  LINT_INIT(remove_length);

  if (!remove_str || (remove_length=remove_str->length()) == 0 ||
      remove_length > res->length())
    return res;

  char *ptr=(char*) res->ptr();
  char *end=ptr+res->length();
  if (remove_length == 1)
  {
    char chr=(*remove_str)[0];
    while (ptr != end && *ptr == chr)
      ptr++;
  }
  else
  {
    const char *r_ptr=remove_str->ptr();
    end-=remove_length;
    while (ptr < end && !memcmp(ptr,r_ptr,remove_length))
      ptr+=remove_length;
    end+=remove_length;
  }
  if (ptr == res->ptr())
    return res;
  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
  return &tmp_value;
}


String *Item_func_rtrim::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0; /* purecov: inspected */
  char buff[MAX_FIELD_WIDTH];
1153
  String tmp(buff,sizeof(buff),res->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
  String *remove_str=args[1]->val_str(&tmp);
  uint remove_length;
  LINT_INIT(remove_length);

  if (!remove_str || (remove_length=remove_str->length()) == 0 ||
      remove_length > res->length())
    return res;

  char *ptr=(char*) res->ptr();
  char *end=ptr+res->length();
#ifdef USE_MB
  char *p=ptr;
  register uint32 l;
#endif
  if (remove_length == 1)
  {
    char chr=(*remove_str)[0];
#ifdef USE_MB
1172
    if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1173 1174 1175
    {
      while (ptr < end)
      {
1176
	if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
	else ++ptr;
      }
      ptr=p;
    }
#endif
    while (ptr != end  && end[-1] == chr)
      end--;
  }
  else
  {
    const char *r_ptr=remove_str->ptr();
#ifdef USE_MB
1189
    if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1190 1191 1192 1193
    {
  loop:
      while (ptr + remove_length < end)
      {
1194
	if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
	else ++ptr;
      }
      if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
      {
	end-=remove_length;
	ptr=p;
	goto loop;
      }
    }
    else
#endif /* USE_MB */
    {
      while (ptr + remove_length < end &&
	     !memcmp(end-remove_length,r_ptr,remove_length))
	end-=remove_length;
    }
  }
  if (end == res->ptr()+res->length())
    return res;
  tmp_value.set(*res,0,(uint) (end-res->ptr()));
  return &tmp_value;
}


String *Item_func_trim::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;					/* purecov: inspected */
  char buff[MAX_FIELD_WIDTH];
1225
  String tmp(buff,sizeof(buff),res->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
  String *remove_str=args[1]->val_str(&tmp);
  uint remove_length;
  LINT_INIT(remove_length);

  if (!remove_str || (remove_length=remove_str->length()) == 0 ||
      remove_length > res->length())
    return res;

  char *ptr=(char*) res->ptr();
  char *end=ptr+res->length();
  const char *r_ptr=remove_str->ptr();
1237
  while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1238 1239
    ptr+=remove_length;
#ifdef USE_MB
1240
  if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1241 1242 1243 1244 1245 1246
  {
    char *p=ptr;
    register uint32 l;
 loop:
    while (ptr + remove_length < end)
    {
1247
      if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
      else ++ptr;
    }
    if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
    {
      end-=remove_length;
      ptr=p;
      goto loop;
    }
    ptr=p;
  }
  else
#endif /* USE_MB */
  {
1261
    while (ptr + remove_length <= end &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1262 1263 1264 1265 1266 1267 1268 1269 1270
	   !memcmp(end-remove_length,r_ptr,remove_length))
      end-=remove_length;
  }
  if (ptr == res->ptr() && end == ptr+res->length())
    return res;
  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
  return &tmp_value;
}

1271 1272 1273 1274 1275
void Item_func_password::fix_length_and_dec()
{
  max_length= get_password_length(use_old_passwords);
}

peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1276
/*
1277
 Password() function has 2 arguments. Second argument can be used
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1278 1279
 to make results repeatable
*/ 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1280 1281 1282

String *Item_func_password::val_str(String *str)
{
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1283 1284 1285
  struct rand_struct rand_st; // local structure for 2 param version
  ulong  seed=0;              // seed to initialise random generator to
  
1286
  String *res  =args[0]->val_str(str);          
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1287 1288
  if ((null_value=args[0]->null_value))
    return 0;
1289
  
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1290 1291 1292 1293
  if (arg_count == 1)
  {    
    if (res->length() == 0)
      return &empty_string;
1294
    make_scrambled_password(tmp_value,res->c_ptr(),use_old_passwords,
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1295
                            &current_thd->rand);
1296
    str->set(tmp_value,get_password_length(use_old_passwords),res->charset());
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1297 1298 1299 1300
    return str;
  }
  else
  {
1301 1302 1303 1304 1305
   /* We'll need the buffer to get second parameter */
    char key_buff[80];
    String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
    String *key  =args[1]->val_str(&tmp_key_value);          
    
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1306 1307 1308
    /* Check second argument for NULL value. First one is already checked */
    if ((null_value=args[1]->null_value))
      return 0;
1309 1310 1311 1312 1313
      
    /* This shall be done after checking for null for proper results */       
    if (res->length() == 0)
      return &empty_string;  
      
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1314
    /* Generate the seed first this allows to avoid double allocation */  
1315
    char* seed_ptr=key->c_ptr();
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1316 1317
    while (*seed_ptr)
    {
1318
      seed=(seed*211+*seed_ptr) & 0xffffffffL; /* Use simple hashing */
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1319 1320
      seed_ptr++;
    }
1321
    
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1322
    /* Use constants which allow nice random values even with small seed */
1323 1324 1325
    randominit(&rand_st,
	       (ulong) ((ulonglong) seed*111111+33333333L) & (ulong) 0xffffffff,
	       (ulong) ((ulonglong) seed*1111+55555555L) & (ulong) 0xffffffff);
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1326
    
1327
    make_scrambled_password(tmp_value,res->c_ptr(),use_old_passwords,
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1328
                            &rand_st);
1329
    str->set(tmp_value,get_password_length(use_old_passwords),res->charset());
peter@mysql.com's avatar
SCRUM  
peter@mysql.com committed
1330 1331
    return str;
  }       
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1332 1333
}

1334 1335 1336 1337 1338 1339 1340
String *Item_func_old_password::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;
  if (res->length() == 0)
    return &empty_string;
1341
  make_scrambled_password(tmp_value,res->c_ptr(),1,&current_thd->rand);
1342 1343 1344 1345 1346 1347
  str->set(tmp_value,16,res->charset());
  return str;
}



1348
#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363

String *Item_func_encrypt::val_str(String *str)
{
  String *res  =args[0]->val_str(str);

#ifdef HAVE_CRYPT
  char salt[3],*salt_ptr;
  if ((null_value=args[0]->null_value))
    return 0;
  if (res->length() == 0)
    return &empty_string;

  if (arg_count == 1)
  {					// generate random salt
    time_t timestamp=current_thd->query_start();
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1364 1365
    salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
    salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    salt[2] = 0;
    salt_ptr=salt;
  }
  else
  {					// obtain salt from the first two bytes
    String *salt_str=args[1]->val_str(&tmp_value);
    if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
      return 0;
    salt_ptr= salt_str->c_ptr();
  }
  pthread_mutex_lock(&LOCK_crypt);
  char *tmp=crypt(res->c_ptr(),salt_ptr);
1378
  str->set(tmp,(uint) strlen(tmp),res->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
  str->copy();
  pthread_mutex_unlock(&LOCK_crypt);
  return str;
#else
  null_value=1;
  return 0;
#endif	/* HAVE_CRYPT */
}

void Item_func_encode::fix_length_and_dec()
{
  max_length=args[0]->max_length;
  maybe_null=args[0]->maybe_null;
}

String *Item_func_encode::val_str(String *str)
{
  String *res;
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  null_value=0;
  res=copy_if_not_alloced(str,res,res->length());
  sql_crypt.init();
  sql_crypt.encode((char*) res->ptr(),res->length());
  return res;
}

String *Item_func_decode::val_str(String *str)
{
  String *res;
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  null_value=0;
  res=copy_if_not_alloced(str,res,res->length());
  sql_crypt.init();
  sql_crypt.decode((char*) res->ptr(),res->length());
  return res;
}


String *Item_func_database::val_str(String *str)
{
1427 1428
  THD *thd= current_thd;
  if (!thd->db)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1429 1430
    str->length(0);
  else
1431
    str->copy((const char*) thd->db,(uint) strlen(thd->db),
1432
	      system_charset_info, default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1433 1434 1435 1436 1437
  return str;
}

String *Item_func_user::val_str(String *str)
{
1438
  THD          *thd=current_thd;
1439
  CHARSET_INFO *cs= default_charset();
1440 1441
  const char   *host=thd->host ? thd->host : thd->ip ? thd->ip : "";
  uint32       res_length=(strlen(thd->user)+strlen(host)+10) * cs->mbmaxlen;
1442

1443 1444 1445 1446 1447 1448 1449 1450
  if (str->alloc(res_length))
  {
      null_value=1;
      return 0;
  }
  res_length=cs->snprintf(cs, (char*)str->ptr(), res_length, "%s@%s",thd->user,host);
  str->length(res_length);
  str->set_charset(cs);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
  return str;
}

void Item_func_soundex::fix_length_and_dec()
{
  max_length=args[0]->max_length;
  set_if_bigger(max_length,4);
}


  /*
    If alpha, map input letter to soundex code.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1463
    If not alpha and remove_garbage is set then skip to next char
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1464 1465 1466 1467
    else return 0
    */

extern "C" {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1468
extern const char *soundex_map;		// In mysys/static.c
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1469 1470
}

1471
static char get_scode(CHARSET_INFO *cs,char *ptr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1472
{
1473
  uchar ch=my_toupper(cs,*ptr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
  if (ch < 'A' || ch > 'Z')
  {
					// Thread extended alfa (country spec)
    return '0';				// as vokal
  }
  return(soundex_map[ch-'A']);
}


String *Item_func_soundex::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  char last_ch,ch;
1487
  CHARSET_INFO *cs= &my_charset_latin1;
1488

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1489 1490 1491
  if ((null_value=args[0]->null_value))
    return 0; /* purecov: inspected */

1492
  if (tmp_value.alloc(max(res->length(),4)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1493
    return str; /* purecov: inspected */
1494
  char *to= (char *) tmp_value.ptr();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1495
  char *from= (char *) res->ptr(), *end=from+res->length();
1496 1497 1498
  tmp_value.set_charset(cs);
  
  while (from != end && my_isspace(cs,*from)) // Skip pre-space
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1499 1500 1501
    from++; /* purecov: inspected */
  if (from == end)
    return &empty_string;		// No alpha characters.
1502 1503
  *to++ = my_toupper(cs,*from);		// Copy first letter
  last_ch = get_scode(cs,from);		// code of the first letter
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1504 1505 1506 1507 1508 1509
					// for the first 'double-letter check.
					// Loop on input letters until
					// end of input (null) or output
					// letter code count = 3
  for (from++ ; from < end ; from++)
  {
1510
    if (!my_isalpha(cs,*from))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1511
      continue;
1512
    ch=get_scode(cs,from);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1513 1514 1515 1516 1517 1518
    if ((ch != '0') && (ch != last_ch)) // if not skipped or double
    {
       *to++ = ch;			// letter, copy to output
       last_ch = ch;			// save code of last input letter
    }					// for next double-letter check
  }
1519
  for (end=(char*) tmp_value.ptr()+4 ; to < end ; to++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1520 1521
    *to = '0';
  *to=0;				// end string
1522 1523
  tmp_value.length((uint) (to-tmp_value.ptr()));
  return &tmp_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
}


/*
** Change a number to format '3,333,333,333.000'
** This should be 'internationalized' sometimes.
*/

Item_func_format::Item_func_format(Item *org,int dec) :Item_str_func(org)
{
  decimals=(uint) set_zone(dec,0,30);
}


String *Item_func_format::val_str(String *str)
{
  double nr	=args[0]->val();
  uint32 diff,length,str_length;
  uint dec;
  if ((null_value=args[0]->null_value))
    return 0; /* purecov: inspected */
  dec= decimals ? decimals+1 : 0;
1546
  str->set(nr,decimals,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
  str_length=str->length();
  if (nr < 0)
    str_length--;				// Don't count sign
  length=str->length()+(diff=(str_length- dec-1)/3);
  if (diff)
  {
    char *tmp,*pos;
    str=copy_if_not_alloced(&tmp_str,str,length);
    str->length(length);
    tmp=(char*) str->ptr()+length - dec-1;
    for (pos=(char*) str->ptr()+length ; pos != tmp; pos--)
      pos[0]=pos[- (int) diff];
    while (diff)
    {
      pos[0]=pos[-(int) diff]; pos--;
      pos[0]=pos[-(int) diff]; pos--;
      pos[0]=pos[-(int) diff]; pos--;
      pos[0]=',';
      pos--;
      diff--;
    }
  }
  return str;
}


void Item_func_elt::fix_length_and_dec()
{
  max_length=0;
  decimals=0;
  for (uint i=1 ; i < arg_count ; i++)
  {
    set_if_bigger(max_length,args[i]->max_length);
    set_if_bigger(decimals,args[i]->decimals);
  }
  maybe_null=1;					// NULL if wrong first arg
1583
  with_sum_func= with_sum_func || item->with_sum_func;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1584
  used_tables_cache|=item->used_tables();
1585
  const_item_cache&=item->const_item();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1586 1587 1588
}


1589 1590
void Item_func_elt::split_sum_func(Item **ref_pointer_array,
				   List<Item> &fields)
1591 1592
{
  if (item->with_sum_func && item->type() != SUM_FUNC_ITEM)
1593
    item->split_sum_func(ref_pointer_array, fields);
1594 1595
  else if (item->used_tables() || item->type() == SUM_FUNC_ITEM)
  {
1596
    uint el= fields.elements;
1597
    fields.push_front(item);
1598 1599 1600 1601
    ref_pointer_array[el]= item;
    item= new Item_ref(ref_pointer_array + el, 0, item->name);
  }
  Item_str_func::split_sum_func(ref_pointer_array, fields);
1602 1603 1604
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
void Item_func_elt::update_used_tables()
{
  Item_func::update_used_tables();
  item->update_used_tables();
  used_tables_cache|=item->used_tables();
  const_item_cache&=item->const_item();
}


double Item_func_elt::val()
{
  uint tmp;
  if ((tmp=(uint) item->val_int()) == 0 || tmp > arg_count)
  {
    null_value=1;
    return 0.0;
  }
  null_value=0;
  return args[tmp-1]->val();
}

longlong Item_func_elt::val_int()
{
  uint tmp;
  if ((tmp=(uint) item->val_int()) == 0 || tmp > arg_count)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  return args[tmp-1]->val_int();
}

String *Item_func_elt::val_str(String *str)
{
  uint tmp;
  if ((tmp=(uint) item->val_int()) == 0 || tmp > arg_count)
  {
    null_value=1;
    return NULL;
  }
  null_value=0;
  return args[tmp-1]->val_str(str);
}


1651 1652
void Item_func_make_set::split_sum_func(Item **ref_pointer_array,
					List<Item> &fields)
1653 1654
{
  if (item->with_sum_func && item->type() != SUM_FUNC_ITEM)
1655
    item->split_sum_func(ref_pointer_array, fields);
1656 1657
  else if (item->used_tables() || item->type() == SUM_FUNC_ITEM)
  {
1658
    uint el= fields.elements;
1659
    fields.push_front(item);
1660 1661 1662 1663
    ref_pointer_array[el]= item;
    item= new Item_ref(ref_pointer_array + el, 0, item->name);
  }
  Item_str_func::split_sum_func(ref_pointer_array, fields);
1664 1665 1666
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1667 1668 1669 1670 1671 1672
void Item_func_make_set::fix_length_and_dec()
{
  max_length=arg_count-1;
  for (uint i=1 ; i < arg_count ; i++)
    max_length+=args[i]->max_length;
  used_tables_cache|=item->used_tables();
1673
  const_item_cache&=item->const_item();
1674
  with_sum_func= with_sum_func || item->with_sum_func;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
}


void Item_func_make_set::update_used_tables()
{
  Item_func::update_used_tables();
  item->update_used_tables();
  used_tables_cache|=item->used_tables();
  const_item_cache&=item->const_item();
}


String *Item_func_make_set::val_str(String *str)
{
  ulonglong bits;
  bool first_found=0;
  Item **ptr=args;
  String *result=&empty_string;

  bits=item->val_int();
  if ((null_value=item->null_value))
    return NULL;

  if (arg_count < 64)
    bits &= ((ulonglong) 1 << arg_count)-1;

  for (; bits; bits >>= 1, ptr++)
  {
    if (bits & 1)
    {
      String *res= (*ptr)->val_str(str);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1706
      if (res)					// Skip nulls
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
      {
	if (!first_found)
	{					// First argument
	  first_found=1;
	  if (res != str)
	    result=res;				// Use original string
	  else
	  {
	    if (tmp_str.copy(*res))		// Don't use 'str'
	      return &empty_string;
	    result= &tmp_str;
	  }
	}
	else
	{
	  if (result != &tmp_str)
	  {					// Copy data to tmp_str
	    if (tmp_str.alloc(result->length()+res->length()+1) ||
		tmp_str.copy(*result))
	      return &empty_string;
	    result= &tmp_str;
	  }
	  if (tmp_str.append(',') || tmp_str.append(*res))
	    return &empty_string;
	}
      }
    }
  }
  return result;
}


String *Item_func_char::val_str(String *str)
{
  str->length(0);
  for (uint i=0 ; i < arg_count ; i++)
  {
    int32 num=(int32) args[i]->val_int();
    if (!args[i]->null_value)
#ifdef USE_MB
1747
      if (use_mb(charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1748 1749 1750 1751 1752 1753 1754
      {
        if (num&0xFF000000L) {
           str->append((char)(num>>24));
           goto b2;
        } else if (num&0xFF0000L) {
b2:        str->append((char)(num>>16));
           goto b1;
1755
        } else if (num&0xFF00L) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
b1:        str->append((char)(num>>8));
        }
      }
#endif
      str->append((char)num);
  }
  str->realloc(str->length());			// Add end 0 (for Purify)
  return str;
}


inline String* alloc_buffer(String *res,String *str,String *tmp_value,
			    ulong length)
{
  if (res->alloced_length() < length)
  {
    if (str->alloced_length() >= length)
    {
      (void) str->copy(*res);
      str->length(length);
      return str;
    }
    else
    {
      if (tmp_value->alloc(length))
	return 0;
      (void) tmp_value->copy(*res);
      tmp_value->length(length);
      return tmp_value;
    }
  }
  res->length(length);
  return res;
}


void Item_func_repeat::fix_length_and_dec()
{
  if (args[1]->const_item())
  {
    max_length=(long) (args[0]->max_length * args[1]->val_int());
    if (max_length >= MAX_BLOB_WIDTH)
    {
      max_length=MAX_BLOB_WIDTH;
      maybe_null=1;
    }
  }
  else
  {
    max_length=MAX_BLOB_WIDTH;
    maybe_null=1;
  }
}

/*
** Item_func_repeat::str is carefully written to avoid reallocs
** as much as possible at the cost of a local buffer
*/

String *Item_func_repeat::val_str(String *str)
{
  uint length,tot_length;
  char *to;
  long count= (long) args[1]->val_int();
  String *res =args[0]->val_str(str);

  if (args[0]->null_value || args[1]->null_value)
    goto err;				// string and/or delim are null
  null_value=0;
  if (count <= 0)			// For nicer SQL code
    return &empty_string;
  if (count == 1)			// To avoid reallocs
    return res;
  length=res->length();
1830 1831
  // Safe length check
  if (length > current_thd->variables.max_allowed_packet/count)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
    goto err;				// Probably an error
  tot_length= length*(uint) count;
  if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
    goto err;

  to=(char*) res->ptr()+length;
  while (--count)
  {
    memcpy(to,res->ptr(),length);
    to+=length;
  }
  return (res);

err:
  null_value=1;
  return 0;
}


void Item_func_rpad::fix_length_and_dec()
{
  if (args[1]->const_item())
  {
    uint32 length= (uint32) args[1]->val_int();
    max_length=max(args[0]->max_length,length);
    if (max_length >= MAX_BLOB_WIDTH)
    {
      max_length=MAX_BLOB_WIDTH;
      maybe_null=1;
    }
  }
  else
  {
    max_length=MAX_BLOB_WIDTH;
    maybe_null=1;
  }
}


String *Item_func_rpad::val_str(String *str)
{
  uint32 res_length,length_pad;
  char *to;
  const char *ptr_pad;
  int32 count= (int32) args[1]->val_int();
  String *res =args[0]->val_str(str);
  String *rpad = args[2]->val_str(str);

  if (!res || args[1]->null_value || !rpad)
    goto err;
  null_value=0;
  if (count <= (int32) (res_length=res->length()))
1884 1885 1886 1887
  {						// String to pad is big enough
    res->length(count);				// Shorten result if longer
    return (res);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1888
  length_pad= rpad->length();
1889 1890
  if ((ulong) count > current_thd->variables.max_allowed_packet ||
      args[2]->null_value || !length_pad)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
    goto err;
  if (!(res= alloc_buffer(res,str,&tmp_value,count)))
    goto err;

  to= (char*) res->ptr()+res_length;
  ptr_pad=rpad->ptr();
  for (count-= res_length; (uint32) count > length_pad; count-= length_pad)
  {
    memcpy(to,ptr_pad,length_pad);
    to+= length_pad;
  }
  memcpy(to,ptr_pad,(size_t) count);
  return (res);

 err:
  null_value=1;
  return 0;
}


void Item_func_lpad::fix_length_and_dec()
{
  if (args[1]->const_item())
  {
    uint32 length= (uint32) args[1]->val_int();
    max_length=max(args[0]->max_length,length);
    if (max_length >= MAX_BLOB_WIDTH)
    {
      max_length=MAX_BLOB_WIDTH;
      maybe_null=1;
    }
  }
  else
  {
    max_length=MAX_BLOB_WIDTH;
    maybe_null=1;
  }
}


String *Item_func_lpad::val_str(String *str)
{
  uint32 res_length,length_pad;
  char *to;
  const char *ptr_pad;
  ulong count= (long) args[1]->val_int();
  String *res= args[0]->val_str(str);
  String *lpad= args[2]->val_str(str);

  if (!res || args[1]->null_value || !lpad)
    goto err;
  null_value=0;
  if (count <= (res_length=res->length()))
1944 1945 1946 1947
  {						// String to pad is big enough
    res->length(count);				// Shorten result if longer
    return (res);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1948
  length_pad= lpad->length();
1949 1950
  if (count > current_thd->variables.max_allowed_packet ||
      args[2]->null_value || !length_pad)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
    goto err;

  if (res->alloced_length() < count)
  {
    if (str->alloced_length() >= count)
    {
      memcpy((char*) str->ptr()+(count-res_length),res->ptr(),res_length);
      res=str;
    }
    else
    {
      if (tmp_value.alloc(count))
	goto err;
      memcpy((char*) tmp_value.ptr()+(count-res_length),res->ptr(),res_length);
      res=&tmp_value;
    }
  }
  else
    bmove_upp((char*) res->ptr()+count,res->ptr()+res_length,res_length);
  res->length(count);

  to= (char*) res->ptr();
  ptr_pad= lpad->ptr();
  for (count-= res_length; count > length_pad; count-= length_pad)
  {
    memcpy(to,ptr_pad,length_pad);
    to+= length_pad;
  }
  memcpy(to,ptr_pad,(size_t) count);
  return (res);

 err:
  null_value=1;
  return 0;
}


String *Item_func_conv::val_str(String *str)
{
  String *res= args[0]->val_str(str);
  char *endptr,ans[65],*ptr;
  longlong dec;
  int from_base= (int) args[1]->val_int();
  int to_base= (int) args[2]->val_int();
1995
  int err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005

  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
      abs(to_base) > 36 || abs(to_base) < 2 ||
      abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  if (from_base < 0)
2006
    dec= my_strntoll(res->charset(),res->ptr(),res->length(),-from_base,&endptr,&err);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2007
  else
2008
    dec= (longlong) my_strntoull(res->charset(),res->ptr(),res->length(),from_base,&endptr,&err);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2009
  ptr= longlong2str(dec,ans,to_base);
2010
  if (str->copy(ans,(uint32) (ptr-ans), default_charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2011 2012 2013 2014
    return &empty_string;
  return str;
}

2015

2016 2017 2018 2019 2020 2021
String *Item_func_conv_charset::val_str(String *str)
{
  my_wc_t wc;
  int cnvres;
  const uchar *s, *se;
  uchar *d, *d0, *de;
2022
  uint32 dmaxlen;
2023 2024
  String *arg= args[0]->val_str(str);
  CHARSET_INFO *from,*to;
2025

2026 2027 2028 2029 2030
  if (!arg)
  {
    null_value=1;
    return 0;
  }
bar@gw.udmsearch.izhnet.ru's avatar
Fix  
bar@gw.udmsearch.izhnet.ru committed
2031
  null_value=0;
2032

2033 2034 2035 2036 2037
  from=arg->charset();
  to=conv_charset;

  s=(const uchar*)arg->ptr();
  se=s+arg->length();
2038

2039
  dmaxlen=arg->length()*to->mbmaxlen+1;
2040 2041 2042
  str->alloc(dmaxlen);
  d0=d=(unsigned char*)str->ptr();
  de=d+dmaxlen;
2043

2044
  while (1)
2045
  {
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
    cnvres=from->mb_wc(from,&wc,s,se);
    if (cnvres>0)
    {
      s+=cnvres;
    }
    else if (cnvres==MY_CS_ILSEQ)
    {
      s++;
      wc='?';
    }
    else
      break;

outp:
    cnvres=to->wc_mb(to,wc,d,de);
    if (cnvres>0)
    {
      d+=cnvres;
    }
    else if (cnvres==MY_CS_ILUNI && wc!='?')
    {
        wc='?';
        goto outp;
    }
    else
      break;
  };
2073

2074
  str->length((uint32) (d-d0));
2075 2076 2077 2078 2079 2080
  str->set_charset(to);
  return str;
}

void Item_func_conv_charset::fix_length_and_dec()
{
2081
  max_length = args[0]->max_length*conv_charset->mbmaxlen;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2082
  coercibility= COER_IMPLICIT;
2083
  set_charset(conv_charset);
2084 2085
}

2086

2087

2088 2089 2090 2091 2092 2093
String *Item_func_conv_charset3::val_str(String *str)
{
  my_wc_t wc;
  int cnvres;
  const uchar *s, *se;
  uchar *d, *d0, *de;
2094
  uint32 dmaxlen;
2095 2096 2097 2098 2099
  String *arg= args[0]->val_str(str);
  String *to_cs= args[1]->val_str(str);
  String *from_cs= args[2]->val_str(str);
  CHARSET_INFO *from_charset;
  CHARSET_INFO *to_charset;
2100 2101 2102

  if (!arg     || args[0]->null_value ||
      !to_cs   || args[1]->null_value ||
2103
      !from_cs || args[2]->null_value ||
2104 2105
      !(from_charset=get_charset_by_name(from_cs->ptr(), MYF(MY_WME))) ||
      !(to_charset=get_charset_by_name(to_cs->ptr(), MYF(MY_WME))))
2106 2107 2108 2109 2110 2111 2112
  {
    null_value=1;
    return 0;
  }

  s=(const uchar*)arg->ptr();
  se=s+arg->length();
2113

2114
  dmaxlen=arg->length()*to_charset->mbmaxlen+1;
2115 2116 2117
  str->alloc(dmaxlen);
  d0=d=(unsigned char*)str->ptr();
  de=d+dmaxlen;
2118

2119 2120
  while (1)
  {
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
    cnvres=from_charset->mb_wc(from_charset,&wc,s,se);
    if (cnvres>0)
    {
      s+=cnvres;
    }
    else if (cnvres==MY_CS_ILSEQ)
    {
      s++;
      wc='?';
    }
    else
      break;

outp:
    cnvres=to_charset->wc_mb(to_charset,wc,d,de);
    if (cnvres>0)
    {
      d+=cnvres;
    }
    else if (cnvres==MY_CS_ILUNI && wc!='?')
    {
        wc='?';
        goto outp;
    }
    else
      break;
  };
2148

2149
  str->length((uint32) (d-d0));
2150 2151 2152 2153
  str->set_charset(to_charset);
  return str;
}

2154

2155
bool Item_func_conv_charset::fix_fields(THD *thd,struct st_table_list *tables, Item **ref)
2156 2157 2158 2159
{
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
  used_tables_cache=0;
  const_item_cache=1;
2160

2161 2162
  if (thd && check_stack_overrun(thd,buff))
    return 0;					// Fatal error if flag is set!
2163
  if (args[0]->fix_fields(thd, tables, args) || args[0]->check_cols(1))
2164 2165
    return 1;
  maybe_null=args[0]->maybe_null;
2166
  const_item_cache=args[0]->const_item();
2167
  set_charset(conv_charset);
2168
  fix_length_and_dec();
2169
  fixed= 1;
2170
  return 0;
2171 2172 2173
}


2174 2175
void Item_func_conv_charset3::fix_length_and_dec()
{
2176
  max_length = args[0]->max_length;
2177 2178
}

2179 2180 2181
String *Item_func_set_collation::val_str(String *str)
{
  str=args[0]->val_str(str);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2182 2183
  if ((null_value=args[0]->null_value))
    return 0;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2184
  str->set_charset(charset());
2185 2186 2187
  return str;
}

2188
bool Item_func_set_collation::fix_fields(THD *thd,struct st_table_list *tables, Item **ref)
2189
{
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2190 2191 2192
  CHARSET_INFO *set_collation;
  String tmp, *str;
  const char *colname;
2193 2194 2195
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
  used_tables_cache=0;
  const_item_cache=1;
2196

2197 2198
  if (thd && check_stack_overrun(thd,buff))
    return 0;					// Fatal error if flag is set!
2199
  if (args[0]->fix_fields(thd, tables, args) || args[0]->check_cols(1))
2200
    return 1;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
  if (args[0]->fix_fields(thd, tables, args) || args[0]->check_cols(1))
    return 2;
  maybe_null=args[0]->maybe_null || args[1]->maybe_null;

  str= args[1]->val_str(&tmp);
  colname= str->c_ptr();
  if (!strncmp(colname,"BINARY",6))
    set_collation= get_charset_by_csname(args[0]->charset()->csname,
					 MY_CS_BINSORT,MYF(0));
  else
    set_collation= get_charset_by_name(colname,MYF(0));
  
  if (!set_collation)
  {
    my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), str->c_ptr());
    return 1;
  }
  
2219
  if (!my_charset_same(args[0]->charset(),set_collation))
2220
  {
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2221 2222 2223
    my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), 
      set_collation->name,args[0]->charset()->csname);
    return 1;
2224
  }
2225
  set_charset(set_collation);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2226
  
2227
  coercibility= COER_EXPLICIT;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2228 2229 2230
  with_sum_func= with_sum_func || args[0]->with_sum_func;
  used_tables_cache=args[0]->used_tables();
  const_item_cache=args[0]->const_item();
2231
  fix_length_and_dec();
2232
  fixed= 1;
2233 2234 2235
  return 0;
}

2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
{
  /* Assume we don't have rtti */
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM)
    return 0;
  Item_func *item_func=(Item_func*) item;
  if (arg_count != item_func->arg_count ||
      func_name() != item_func->func_name())
    return 0;
  Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2248
  if (charset() != item_func_sc->charset())
2249 2250 2251 2252 2253 2254 2255
    return 0;
  for (uint i=0; i < arg_count ; i++)
    if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
      return 0;
  return 1;
}

2256 2257 2258 2259
String *Item_func_charset::val_str(String *str)
{
  String *res = args[0]->val_str(str);

2260 2261 2262
  if ((null_value=(args[0]->null_value || !res->charset())))
    return 0;
  str->copy(res->charset()->csname,strlen(res->charset()->csname),
2263
	    &my_charset_latin1, default_charset());
2264 2265 2266 2267 2268 2269 2270
  return str;
}

String *Item_func_collation::val_str(String *str)
{
  String *res = args[0]->val_str(str);

2271 2272
  if ((null_value=(args[0]->null_value || !res->charset())))
    return 0;
2273
  str->copy(res->charset()->name,strlen(res->charset()->name),
2274
	    &my_charset_latin1, default_charset());
2275 2276
  return str;
}
2277 2278


2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
String *Item_func_hex::val_str(String *str)
{
  if (args[0]->result_type() != STRING_RESULT)
  {
    /* Return hex of unsigned longlong value */
    longlong dec= args[0]->val_int();
    char ans[65],*ptr;
    if ((null_value= args[0]->null_value))
      return 0;
    ptr= longlong2str(dec,ans,16);
2289
    if (str->copy(ans,(uint32) (ptr-ans),default_charset_info))
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
      return &empty_string;			// End of memory
    return str;
  }

  /* Convert given string to a hex string, character by character */
  String *res= args[0]->val_str(str);
  const char *from, *end;
  char *to;
  if (!res || tmp_value.alloc(res->length()*2))
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  tmp_value.length(res->length()*2);
  for (from=res->ptr(), end=from+res->length(), to= (char*) tmp_value.ptr();
       from != end ;
       from++, to+=2)
  {
    uint tmp=(uint) (uchar) *from;
    to[0]=_dig_vec[tmp >> 4];
    to[1]=_dig_vec[tmp & 15];
  }
  return &tmp_value;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
#include <my_dir.h>				// For my_stat

String *Item_load_file::val_str(String *str)
{
  String *file_name;
  File file;
  MY_STAT stat_info;
  DBUG_ENTER("load_file");

  if (!(file_name= args[0]->val_str(str)) ||
      !(current_thd->master_access & FILE_ACL) ||
2328
      !my_stat(file_name->c_ptr(), &stat_info, MYF(MY_WME)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2329 2330 2331 2332 2333 2334
    goto err;
  if (!(stat_info.st_mode & S_IROTH))
  {
    /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
    goto err;
  }
2335
  if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
  {
    /* my_error(ER_TOO_LONG_STRING, MYF(0), file_name->c_ptr()); */
    goto err;
  }
  if (tmp_value.alloc(stat_info.st_size))
    goto err;
  if ((file = my_open(file_name->c_ptr(), O_RDONLY, MYF(0))) < 0)
    goto err;
  if (my_read(file, (byte*) tmp_value.ptr(), stat_info.st_size, MYF(MY_NABP)))
  {
    my_close(file, MYF(0));
    goto err;
  }
  tmp_value.length(stat_info.st_size);
  my_close(file, MYF(0));
  null_value = 0;
  return &tmp_value;

err:
  null_value = 1;
  DBUG_RETURN(0);
}


String* Item_func_export_set::val_str(String* str)
{
  ulonglong the_set = (ulonglong) args[0]->val_int();
2363
  String yes_buf, *yes;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2364
  yes = args[1]->val_str(&yes_buf);
2365
  String no_buf, *no;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2366
  no = args[2]->val_str(&no_buf);
2367
  String *sep = NULL, sep_buf ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397

  uint num_set_values = 64;
  ulonglong mask = 0x1;
  str->length(0);

  /* Check if some argument is a NULL value */
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
  {
    null_value=1;
    return 0;
  }
  switch(arg_count) {
  case 5:
    num_set_values = (uint) args[4]->val_int();
    if (num_set_values > 64)
      num_set_values=64;
    if (args[4]->null_value)
    {
      null_value=1;
      return 0;
    }
    /* Fall through */
  case 4:
    if (!(sep = args[3]->val_str(&sep_buf)))	// Only true if NULL
    {
      null_value=1;
      return 0;
    }
    break;
  case 3:
2398
    sep_buf.set(",", 1, default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
    sep = &sep_buf;
  }
  null_value=0;

  for (uint i = 0; i < num_set_values; i++, mask = (mask << 1))
  {
    if (the_set & mask)
      str->append(*yes);
    else
      str->append(*no);
2409
    if (i != num_set_values - 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
      str->append(*sep);
  }
  return str;
}

void Item_func_export_set::fix_length_and_dec()
{
  uint length=max(args[1]->max_length,args[2]->max_length);
  uint sep_length=(arg_count > 3 ? args[3]->max_length : 1);
  max_length=length*64+sep_length*63;
}

String* Item_func_inet_ntoa::val_str(String* str)
{
  uchar buf[8], *p;
  ulonglong n = (ulonglong) args[0]->val_int();
  char num[4];
2427

2428
  /*
2429
    We do not know if args[0] is NULL until we have called
2430
    some val function on it if args[0] is not a constant!
2431 2432

    Also return null if n > 255.255.255.255
2433
  */
2434
  if ((null_value= (args[0]->null_value || n > (ulonglong) LL(4294967295))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2435
    return 0;					// Null value
2436

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2437
  str->length(0);
2438
  int4store(buf,n);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2439

2440
  /* Now we can assume little endian. */
2441

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2442
  num[3]='.';
2443
  for (p=buf+4 ; p-- > buf ; )
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
  {
    uint c = *p;
    uint n1,n2;					// Try to avoid divisions
    n1= c / 100;				// 100 digits
    c-= n1*100;
    n2= c / 10;					// 10 digits
    c-=n2*10;					// last digit
    num[0]=(char) n1+'0';
    num[1]=(char) n2+'0';
    num[2]=(char) c+'0';
    uint length=(n1 ? 4 : n2 ? 3 : 2);		// Remove pre-zero

    (void) str->append(num+4-length,length);
  }
  str->length(str->length()-1);			// Remove last '.';
  return str;
}
2461

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2462

2463
/*
2464 2465 2466 2467 2468 2469
  QUOTE() function returns argument string in single quotes suitable for
  using in a SQL statement.

  DESCRIPTION
    Adds a \ before all characters that needs to be escaped in a SQL string.
    We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
2470
    running commands from a file in windows.
2471 2472 2473 2474 2475 2476

    This function is very useful when you want to generate SQL statements

    RETURN VALUES
    str		Quoted string
    NULL	Argument to QUOTE() was NULL or out of memory.
2477
*/
2478 2479 2480

#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))

2481 2482
String *Item_func_quote::val_str(String *str)
{
2483 2484 2485
  /*
    Bit mask that has 1 for set for the position of the following characters:
    0, \, ' and ^Z
2486
  */
2487

2488
  static uchar escmask[32]=
2489 2490 2491 2492 2493 2494
  {
    0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  };
2495

2496 2497 2498 2499
  char *from, *to, *end, *start;
  String *arg= args[0]->val_str(str);
  uint arg_length, new_length;
  if (!arg)					// Null argument
2500
    goto null;
2501 2502
  arg_length= arg->length();
  new_length= arg_length+2; /* for beginning and ending ' signs */
2503

2504 2505
  for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
    new_length+= get_esc_bit(escmask, *from);
ram@ram.(none)'s avatar
ram@ram.(none) committed
2506

2507 2508 2509 2510 2511
  /*
    We have to use realloc() instead of alloc() as we want to keep the
    old result in str
  */
  if (str->realloc(new_length))
2512
    goto null;
2513 2514 2515 2516 2517 2518

  /*
    As 'arg' and 'str' may be the same string, we must replace characters
    from the end to the beginning
  */
  to= (char*) str->ptr() + new_length - 1;
2519
  *to--= '\'';
ram@mysql.r18.ru's avatar
ram@mysql.r18.ru committed
2520
  for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
2521
  {
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
    /*
      We can't use the bitmask here as we want to replace \O and ^Z with 0
      and Z
    */
    switch (*end)  {
    case 0:
      *to--= '0';
      *to=   '\\';
      break;
    case '\032':
      *to--= 'Z';
      *to=   '\\';
      break;
    case '\'':
    case '\\':
      *to--= *end;
      *to=   '\\';
      break;
    default:
      *to= *end;
      break;
    }
2544
  }
2545
  *to= '\'';
2546
  str->length(new_length);
2547
  return str;
2548 2549 2550 2551

null:
  null_value= 1;
  return 0;
2552
}
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2553 2554


2555 2556 2557 2558 2559 2560 2561
/*******************************************************
General functions for spatial objects
********************************************************/

String *Item_func_geometry_from_text::val_str(String *str)
{
  Geometry geom;
hf@deer.mysql.r18.ru's avatar
hf@deer.mysql.r18.ru committed
2562 2563
  String arg_val;
  String *wkt = args[0]->val_str(&arg_val);
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
  GTextReadStream trs(wkt->ptr(), wkt->length());

  str->length(0);
  if ((null_value=(args[0]->null_value || geom.create_from_wkt(&trs, str, 0))))
    return 0;
  return str;
}


void Item_func_geometry_from_text::fix_length_and_dec()
{
  max_length=MAX_BLOB_WIDTH;
}


String *Item_func_as_text::val_str(String *str)
{
hf@deer.mysql.r18.ru's avatar
hf@deer.mysql.r18.ru committed
2581 2582
  String arg_val;
  String *wkt = args[0]->val_str(&arg_val);
2583
  Geometry geom;
2584

2585
  if ((null_value=(args[0]->null_value ||
2586
                   geom.create_from_wkb(wkt->ptr(),wkt->length()))))
2587 2588 2589 2590 2591
    return 0;

  str->length(0);

  if ((null_value=geom.as_wkt(str)))
2592
    return 0;
2593

2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
  return str;
}

void Item_func_as_text::fix_length_and_dec()
{
  max_length=MAX_BLOB_WIDTH;
}

String *Item_func_geometry_type::val_str(String *str)
{
  String *wkt = args[0]->val_str(str);
  Geometry geom;

  if ((null_value=(args[0]->null_value ||
                   geom.create_from_wkb(wkt->ptr(),wkt->length()))))
    return 0;
2610 2611 2612
  str->copy(geom.get_class_info()->m_name,
	    strlen(geom.get_class_info()->m_name),
	    default_charset_info);
2613 2614 2615 2616 2617 2618
  return str;
}


String *Item_func_envelope::val_str(String *str)
{
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2619
  String *res = args[0]->val_str(str);
2620
  Geometry geom;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2621 2622 2623 2624 2625 2626 2627
  
  if ((null_value = args[0]->null_value ||
               geom.create_from_wkb(res->ptr(),res->length())))
    return 0;
  
  res->length(0);
  return (null_value= geom.envelope(res)) ? 0 : res;
2628 2629 2630 2631 2632
}


String *Item_func_centroid::val_str(String *str)
{
hf@deer.mysql.r18.ru's avatar
hf@deer.mysql.r18.ru committed
2633 2634
  String arg_val;
  String *wkb = args[0]->val_str(&arg_val);
2635 2636 2637
  Geometry geom;

  null_value = args[0]->null_value ||
2638
               geom.create_from_wkb(wkb->ptr(),wkb->length()) ||
2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
               !GEOM_METHOD_PRESENT(geom,centroid) ||
               geom.centroid(str);

  return null_value ? 0: str;
}


/***********************************************
  Spatial decomposition functions
***********************************************/

String *Item_func_spatial_decomp::val_str(String *str)
{
hf@deer.mysql.r18.ru's avatar
hf@deer.mysql.r18.ru committed
2652 2653
  String arg_val;
  String *wkb = args[0]->val_str(&arg_val);
2654 2655 2656 2657 2658 2659 2660
  Geometry geom;

  if ((null_value = (args[0]->null_value ||
                     geom.create_from_wkb(wkb->ptr(),wkb->length()))))
    return 0;

  null_value=1;
hf@deer.mysql.r18.ru's avatar
hf@deer.mysql.r18.ru committed
2661
  str->length(0);
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
  switch(decomp_func)
  {
    case SP_STARTPOINT:
      if (!GEOM_METHOD_PRESENT(geom,start_point) || geom.start_point(str))
        goto ret;
      break;

    case SP_ENDPOINT:
      if (!GEOM_METHOD_PRESENT(geom,end_point) || geom.end_point(str))
        goto ret;
      break;

    case SP_EXTERIORRING:
      if (!GEOM_METHOD_PRESENT(geom,exterior_ring) || geom.exterior_ring(str))
        goto ret;
      break;

    default:
      goto ret;
  }
  null_value=0;

2684
ret:
2685 2686 2687 2688 2689 2690
  return null_value ? 0 : str;
}


String *Item_func_spatial_decomp_n::val_str(String *str)
{
hf@deer.mysql.r18.ru's avatar
hf@deer.mysql.r18.ru committed
2691 2692
  String arg_val;
  String *wkb  =        args[0]->val_str(&arg_val);
2693 2694 2695
  long n       = (long) args[1]->val_int();
  Geometry geom;

2696
  if ((null_value = (args[0]->null_value ||
2697 2698 2699 2700 2701 2702 2703 2704 2705
                     args[1]->null_value ||
                     geom.create_from_wkb(wkb->ptr(),wkb->length()) )))
    return 0;

  null_value=1;

  switch(decomp_func_n)
  {
    case SP_POINTN:
2706
      if (!GEOM_METHOD_PRESENT(geom,point_n) ||
2707 2708 2709 2710 2711
          geom.point_n(n,str))
        goto ret;
      break;

    case SP_GEOMETRYN:
2712
      if (!GEOM_METHOD_PRESENT(geom,geometry_n) ||
2713 2714 2715 2716 2717
          geom.geometry_n(n,str))
        goto ret;
      break;

    case SP_INTERIORRINGN:
2718
      if (!GEOM_METHOD_PRESENT(geom,interior_ring_n) ||
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
          geom.interior_ring_n(n,str))
        goto ret;
      break;

    default:
      goto ret;
  }
  null_value=0;

ret:
  return null_value ? 0 : str;
}



/***********************************************
Functions to concatinate various spatial objects
************************************************/


/*
*  Concatinate doubles into Point
*/


String *Item_func_point::val_str(String *str)
{
2746 2747 2748
  double x= args[0]->val();
  double y= args[1]->val();

2749
  if ( (null_value = (args[0]->null_value ||
2750 2751 2752 2753 2754 2755 2756
                     args[1]->null_value ||
                     str->realloc(1+4+8+8))))
    return 0;

  str->length(0);
  str->q_append((char)Geometry::wkbNDR);
  str->q_append((uint32)Geometry::wkbPoint);
2757 2758
  str->q_append(x);
  str->q_append(y);
2759 2760 2761 2762 2763
  return str;
}


/*
2764
  Concatinates various items into various collections
2765 2766 2767 2768
  with checkings for valid wkb type of items.
  For example, MultiPoint can be a collection of Points only.
  coll_type contains wkb type of target collection.
  item_type contains a valid wkb type of items.
2769
  In the case when coll_type is wkbGeometryCollection,
2770 2771 2772 2773 2774
  we do not check wkb type of items, any is valid.
*/

String *Item_func_spatial_collection::val_str(String *str)
{
hf@deer.mysql.r18.ru's avatar
hf@deer.mysql.r18.ru committed
2775
  String arg_value;
2776 2777 2778 2779 2780
  uint i;

  null_value=1;

  str->length(0);
2781
  if (str->reserve(9,512))
2782 2783 2784 2785 2786 2787 2788 2789
    return 0;

  str->q_append((char)Geometry::wkbNDR);
  str->q_append((uint32)coll_type);
  str->q_append((uint32)arg_count);

  for (i = 0; i < arg_count; ++i)
  {
2790
    String *res = args[i]->val_str(&arg_value);
2791 2792 2793 2794 2795
    if (args[i]->null_value)
      goto ret;

    if ( coll_type == Geometry::wkbGeometryCollection )
    {
2796 2797
      /*
         In the case of GeometryCollection we don't need
2798 2799 2800 2801 2802
         any checkings for item types, so just copy them
         into target collection
      */
      if ((null_value=(str->reserve(res->length(),512))))
        goto ret;
2803

2804 2805 2806 2807
      str->q_append(res->ptr(),res->length());
    }
    else
    {
2808 2809
      enum Geometry::wkbType wkb_type;
      uint32 len=res->length();
2810 2811
      const char *data=res->ptr()+1;

2812 2813
      /*
         In the case of named collection we must to
2814 2815 2816
         check that items are of specific type, let's
         do this checking now
      */
2817

2818
      if (len < 5)
2819
        goto ret;
2820
      wkb_type= (Geometry::wkbType) uint4korr(data);
2821 2822
      data+=4;
      len-=5;
2823
      if (wkb_type != item_type)
2824
        goto ret;
2825

2826 2827 2828 2829
      switch (coll_type) {
      case Geometry::wkbMultiPoint:
      case Geometry::wkbMultiLineString:
      case Geometry::wkbMultiPolygon:
2830
	if (len < WKB_HEADER_SIZE)
2831
	  goto ret;
2832

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2833 2834
	data-=WKB_HEADER_SIZE;
	len+=WKB_HEADER_SIZE;
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
	if (str->reserve(len,512))
	  goto ret;
	str->q_append(data,len);
	break;

      case Geometry::wkbLineString:
	if (str->reserve(POINT_DATA_SIZE,512))
	  goto ret;
	str->q_append(data,POINT_DATA_SIZE);
	break;

      case Geometry::wkbPolygon:
2847
      {
2848 2849 2850
	uint32 n_points;
	double x1, y1, x2, y2;

ram@mysql.r18.ru's avatar
ram@mysql.r18.ru committed
2851
	if (len < 4 + 2 * POINT_DATA_SIZE)
2852 2853 2854 2855
	  goto ret;

	uint32 llen=len;
	const char *ldata=data;
2856

2857 2858 2859 2860 2861 2862
	n_points=uint4korr(data);
	data+=4;
	float8get(x1,data);
	data+=8;
	float8get(y1,data);
	data+=8;
2863

2864
	data+=(n_points-2) * POINT_DATA_SIZE;
2865

2866 2867
	float8get(x2,data);
	float8get(y2,data+8);
2868

2869 2870
	if ((x1 != x2) || (y1 != y2))
	  goto ret;
2871

2872 2873 2874 2875 2876
	if (str->reserve(llen,512))
	  goto ret;
	str->q_append(ldata, llen);
      }
      break;
2877

2878 2879
      default:
	goto ret;
2880 2881 2882 2883
      }
    }
  }

2884
  if (str->length() > current_thd->variables.max_allowed_packet)
2885 2886 2887 2888 2889 2890 2891
    goto ret;

  null_value = 0;

ret:
  return null_value ? 0 : str;
}