item_strfunc.cc 120 KB
Newer Older
Kent Boortz's avatar
Kent Boortz committed
1
/*
2
   Copyright (c) 2000, 2017, Oracle and/or its affiliates.
3
   Copyright (c) 2009, 2018, MariaDB Corporation
unknown's avatar
unknown committed
4

unknown's avatar
unknown committed
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
unknown's avatar
unknown committed
7
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
8

unknown's avatar
unknown committed
9 10 11 12
   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.
unknown's avatar
unknown committed
13

unknown's avatar
unknown committed
14 15
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
Kent Boortz's avatar
Kent Boortz committed
16 17
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
*/
unknown's avatar
unknown committed
18

unknown's avatar
unknown committed
19 20 21 22 23 24 25 26 27
/**
  @file

  @brief
  This file defines all string functions

  @warning
    Some string functions don't always put and end-null on a String.
    (This shouldn't be needed)
unknown's avatar
unknown committed
28 29
*/

30
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
31 32 33
#pragma implementation				// gcc: Class implementation
#endif

Konstantin Osipov's avatar
Konstantin Osipov committed
34 35
/* May include caustic 3rd-party defs. Use early, so it can override nothing. */
#include "sha2.h"
36 37 38 39 40 41 42 43 44 45 46
#include "my_global.h"                          // HAVE_*


#include "sql_priv.h"
/*
  It is necessary to include set_var.h instead of item.h because there
  are dependencies on include order for set_var.h and item.h. This
  will be resolved later.
*/
#include "sql_class.h"                          // set_var.h: THD
#include "set_var.h"
Sergei Golubchik's avatar
Sergei Golubchik committed
47 48
#include "sql_base.h"
#include "sql_time.h"
49 50 51 52
#include "sql_acl.h"                            // SUPER_ACL
#include "des_key_file.h"       // st_des_keyschedule, st_des_keyblock
#include "password.h"           // my_make_scrambled_password,
                                // my_make_scrambled_password_323
unknown's avatar
unknown committed
53
#include <m_ctype.h>
54
#include "my_md5.h"
55 56
#include "sha1.h"
#include "my_aes.h"
57
#include <zlib.h>
unknown's avatar
unknown committed
58
C_MODE_START
59
#include "../mysys/my_static.h"			// For soundex_map
unknown's avatar
unknown committed
60
C_MODE_END
unknown's avatar
unknown committed
61

62 63
size_t username_char_length= 16;

64 65 66 67 68 69 70 71 72
/*
  For the Items which have only val_str_ascii() method
  and don't have their own "native" val_str(),
  we provide a "wrapper" method to convert from ASCII
  to Item character set when it's necessary.
  Conversion happens only in case of "tricky" Item character set (e.g. UCS2).
  Normally conversion does not happen, and val_str_ascii() is immediately
  returned instead.
*/
73
String *Item_func::val_str_from_val_str_ascii(String *str, String *str2)
74 75 76 77
{
  DBUG_ASSERT(fixed == 1);

  if (!(collation.collation->state & MY_CS_NONASCII))
78 79 80 81 82 83
  {
    String *res= val_str_ascii(str);
    if (res)
      res->set_charset(collation.collation);
    return res;
  }
84
  
85
  DBUG_ASSERT(str != str2);
86 87
  
  uint errors;
88
  String *res= val_str_ascii(str);
89 90 91
  if (!res)
    return 0;
  
92 93 94
  if ((null_value= str2->copy(res->ptr(), res->length(),
                              &my_charset_latin1, collation.collation,
                              &errors)))
95 96
    return 0;
  
97
  return str2;
98 99 100
}


101 102 103 104 105
/*
  Convert an array of bytes to a hexadecimal representation.

  Used to generate a hexadecimal representation of a message digest.
*/
Konstantin Osipov's avatar
Konstantin Osipov committed
106
static void array_to_hex(char *to, const unsigned char *str, uint len)
107
{
Konstantin Osipov's avatar
Konstantin Osipov committed
108
  const unsigned char *str_end= str + len;
109 110 111 112 113 114
  for (; str != str_end; ++str)
  {
    *to++= _dig_vec_lower[((uchar) *str) >> 4];
    *to++= _dig_vec_lower[((uchar) *str) & 0x0F];
  }
}
115 116


unknown's avatar
unknown committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130
bool Item_str_func::fix_fields(THD *thd, Item **ref)
{
  bool res= Item_func::fix_fields(thd, ref);
  /*
    In Item_str_func::check_well_formed_result() we may set null_value
    flag on the same condition as in test() below.
  */
  maybe_null= (maybe_null ||
               test(thd->variables.sql_mode &
                    (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)));
  return res;
}


131 132 133 134 135 136 137 138 139 140 141 142 143 144
my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(fixed == 1);
  char buff[64];
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
  res= val_str(&tmp);
  if (!res)
    return 0;
  (void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
                       res->length(), res->charset(), decimal_value);
  return decimal_value;
}


145
double Item_str_func::val_real()
unknown's avatar
unknown committed
146
{
147
  DBUG_ASSERT(fixed == 1);
148 149
  int err_not_used;
  char *end_not_used, buff[64];
unknown's avatar
unknown committed
150 151
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
  res= val_str(&tmp);
152 153
  return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
			  &end_not_used, &err_not_used) : 0.0;
unknown's avatar
unknown committed
154 155
}

156

unknown's avatar
unknown committed
157 158
longlong Item_str_func::val_int()
{
159
  DBUG_ASSERT(fixed == 1);
160
  int err;
unknown's avatar
unknown committed
161 162 163
  char buff[22];
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
  res= val_str(&tmp);
unknown's avatar
unknown committed
164 165 166 167
  return (res ?
	  my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL,
		      &err) :
	  (longlong) 0);
unknown's avatar
unknown committed
168 169 170
}


171
String *Item_func_md5::val_str_ascii(String *str)
unknown's avatar
unknown committed
172
{
173
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
174 175 176
  String * sptr= args[0]->val_str(str);
  if (sptr)
  {
unknown's avatar
unknown committed
177
    uchar digest[16];
unknown's avatar
unknown committed
178 179

    null_value=0;
180
    MY_MD5_HASH(digest,(uchar *) sptr->ptr(), sptr->length());
unknown's avatar
unknown committed
181 182 183 184 185
    if (str->alloc(32))				// Ensure that memory is free
    {
      null_value=1;
      return 0;
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
186
    array_to_hex((char *) str->ptr(), digest, 16);
Sergei Golubchik's avatar
Sergei Golubchik committed
187
    str->set_charset(&my_charset_numeric);
unknown's avatar
unknown committed
188 189 190 191 192 193 194 195
    str->length((uint) 32);
    return str;
  }
  null_value=1;
  return 0;
}


196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
/*
  The MD5()/SHA() functions treat their parameter as being a case sensitive.
  Thus we set binary collation on it so different instances of MD5() will be
  compared properly.
*/
static CHARSET_INFO *get_checksum_charset(const char *csname)
{
  CHARSET_INFO *cs= get_charset_by_csname(csname, MY_CS_BINSORT, MYF(0));
  if (!cs)
  {
    // Charset has no binary collation: use my_charset_bin.
    cs= &my_charset_bin;
  }
  return cs;
}


unknown's avatar
unknown committed
213 214
void Item_func_md5::fix_length_and_dec()
{
215 216
  CHARSET_INFO *cs= get_checksum_charset(args[0]->collation.collation->csname);
  args[0]->collation.set(cs, DERIVATION_COERCIBLE);
217
  fix_length_and_charset(32, default_charset());
unknown's avatar
unknown committed
218 219
}

220

221
String *Item_func_sha::val_str_ascii(String *str)
222
{
223
  DBUG_ASSERT(fixed == 1);
224 225 226 227
  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 */
228
    /* Temporary buffer to store 160bit digest */
unknown's avatar
unknown committed
229
    uint8 digest[SHA1_HASH_SIZE];
230
    mysql_sha1_reset(&context);  /* We do not have to check for error here */
231
    /* No need to check error as the only case would be too long message */
232
    mysql_sha1_input(&context,
unknown's avatar
unknown committed
233
                     (const uchar *) sptr->ptr(), sptr->length());
Michael Widenius's avatar
Michael Widenius committed
234

235
    /* Ensure that memory is free and we got result */
236 237
    if (!( str->alloc(SHA1_HASH_SIZE*2) ||
           (mysql_sha1_result(&context,digest))))
238
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
239
      array_to_hex((char *) str->ptr(), digest, SHA1_HASH_SIZE);
Sergei Golubchik's avatar
Sergei Golubchik committed
240
      str->set_charset(&my_charset_numeric);
241 242 243 244
      str->length((uint)  SHA1_HASH_SIZE*2);
      null_value=0;
      return str;
    }
245
  }
246 247 248 249 250 251
  null_value=1;
  return 0;
}

void Item_func_sha::fix_length_and_dec()
{
252 253
  CHARSET_INFO *cs= get_checksum_charset(args[0]->collation.collation->csname);
  args[0]->collation.set(cs, DERIVATION_COERCIBLE);
254 255
  // size of hex representation of hash
  fix_length_and_charset(SHA1_HASH_SIZE * 2, default_charset());
256
}
257

258
String *Item_func_sha2::val_str_ascii(String *str)
Konstantin Osipov's avatar
Konstantin Osipov committed
259 260
{
  DBUG_ASSERT(fixed == 1);
261
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
Konstantin Osipov's avatar
Konstantin Osipov committed
262 263 264 265 266 267
  unsigned char digest_buf[SHA512_DIGEST_LENGTH];
  String *input_string;
  unsigned char *input_ptr;
  size_t input_len;
  uint digest_length= 0;

268
  input_string= args[0]->val_str(str);
Konstantin Osipov's avatar
Konstantin Osipov committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  str->set_charset(&my_charset_bin);

  if (input_string == NULL)
  {
    null_value= TRUE;
    return (String *) NULL;
  }

  null_value= args[0]->null_value;
  if (null_value)
    return (String *) NULL;

  input_ptr= (unsigned char *) input_string->ptr();
  input_len= input_string->length();

  switch ((uint) args[1]->val_int()) {
#ifndef OPENSSL_NO_SHA512
  case 512:
    digest_length= SHA512_DIGEST_LENGTH;
    (void) SHA512(input_ptr, input_len, digest_buf);
    break;
  case 384:
    digest_length= SHA384_DIGEST_LENGTH;
    (void) SHA384(input_ptr, input_len, digest_buf);
    break;
#endif
#ifndef OPENSSL_NO_SHA256
  case 224:
    digest_length= SHA224_DIGEST_LENGTH;
    (void) SHA224(input_ptr, input_len, digest_buf);
    break;
  case 256:
  case 0: // SHA-256 is the default
    digest_length= SHA256_DIGEST_LENGTH;
    (void) SHA256(input_ptr, input_len, digest_buf);
    break;
#endif
  default:
    if (!args[1]->const_item())
      push_warning_printf(current_thd,
        MYSQL_ERROR::WARN_LEVEL_WARN,
        ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
        ER(ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
    null_value= TRUE;
    return NULL;
  }

  /* 
    Since we're subverting the usual String methods, we must make sure that
    the destination has space for the bytes we're about to write.
  */
  str->realloc((uint) digest_length*2 + 1); /* Each byte as two nybbles */

  /* Convert the large number to a string-hex representation. */
  array_to_hex((char *) str->ptr(), digest_buf, digest_length);

  /* We poked raw bytes in.  We must inform the the String of its length. */
  str->length((uint) digest_length*2); /* Each byte as two nybbles */

  null_value= FALSE;
  return str;

#else
  push_warning_printf(current_thd,
    MYSQL_ERROR::WARN_LEVEL_WARN,
    ER_FEATURE_DISABLED,
    ER(ER_FEATURE_DISABLED),
    "sha2", "--with-ssl");
  null_value= TRUE;
  return (String *) NULL;
339
#endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
Konstantin Osipov's avatar
Konstantin Osipov committed
340 341 342 343 344
}


void Item_func_sha2::fix_length_and_dec()
{
unknown's avatar
unknown committed
345
  maybe_null= 1;
Konstantin Osipov's avatar
Konstantin Osipov committed
346 347
  max_length = 0;

348
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
Konstantin Osipov's avatar
Konstantin Osipov committed
349 350 351 352 353
  int sha_variant= args[1]->const_item() ? args[1]->val_int() : 512;

  switch (sha_variant) {
#ifndef OPENSSL_NO_SHA512
  case 512:
354
    fix_length_and_charset(SHA512_DIGEST_LENGTH * 2, default_charset());
Konstantin Osipov's avatar
Konstantin Osipov committed
355 356
    break;
  case 384:
357
    fix_length_and_charset(SHA384_DIGEST_LENGTH * 2, default_charset());
Konstantin Osipov's avatar
Konstantin Osipov committed
358 359 360 361 362
    break;
#endif
#ifndef OPENSSL_NO_SHA256
  case 256:
  case 0: // SHA-256 is the default
363
    fix_length_and_charset(SHA256_DIGEST_LENGTH * 2, default_charset());
Konstantin Osipov's avatar
Konstantin Osipov committed
364 365
    break;
  case 224:
366
    fix_length_and_charset(SHA224_DIGEST_LENGTH * 2, default_charset());
Konstantin Osipov's avatar
Konstantin Osipov committed
367 368 369 370 371 372 373 374 375
    break;
#endif
  default:
    push_warning_printf(current_thd,
      MYSQL_ERROR::WARN_LEVEL_WARN,
      ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
      ER(ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
  }

376 377
  CHARSET_INFO *cs= get_checksum_charset(args[0]->collation.collation->csname);
  args[0]->collation.set(cs, DERIVATION_COERCIBLE);
Konstantin Osipov's avatar
Konstantin Osipov committed
378 379 380 381 382 383 384

#else
  push_warning_printf(current_thd,
    MYSQL_ERROR::WARN_LEVEL_WARN,
    ER_FEATURE_DISABLED,
    ER(ER_FEATURE_DISABLED),
    "sha2", "--with-ssl");
385
#endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
Konstantin Osipov's avatar
Konstantin Osipov committed
386
}
387 388 389

/* Implementation of AES encryption routines */

390 391
String *Item_func_aes_encrypt::val_str(String *str)
{
392
  DBUG_ASSERT(fixed == 1);
393
  char key_buff[80];
394
  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
395 396
  String *sptr= args[0]->val_str(str);			// String to encrypt
  String *key=  args[1]->val_str(&tmp_key_value);	// key
397 398 399 400
  int aes_length;
  if (sptr && key) // we need both arguments to be not NULL
  {
    null_value=0;
401
    aes_length=my_aes_get_size(sptr->length()); // Calculate result length
402

403
    if (!str_value.alloc(aes_length))		// Ensure that memory is free
404 405
    {
      // finally encrypt directly to allocated buffer.
406
      if (my_aes_encrypt(sptr->ptr(),sptr->length(), (char*) str_value.ptr(),
407
			 key->ptr(), key->length()) == aes_length)
408
      {
409
	// We got the expected result length
410 411
	str_value.length((uint) aes_length);
	return &str_value;
412 413 414 415 416 417 418
      }
    }
  }
  null_value=1;
  return 0;
}

419

420 421
void Item_func_aes_encrypt::fix_length_and_dec()
{
422
  max_length=my_aes_get_size(args[0]->max_length);
423 424 425 426 427
}


String *Item_func_aes_decrypt::val_str(String *str)
{
428
  DBUG_ASSERT(fixed == 1);
429
  char key_buff[80];
430 431
  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
  String *sptr, *key;
432 433 434 435 436
  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
437 438
  {
    null_value=0;
439
    if (!str_value.alloc(sptr->length()))  // Ensure that memory is free
440
    {
441
      // finally decrypt directly to allocated buffer.
442 443 444
      int length;
      length=my_aes_decrypt(sptr->ptr(), sptr->length(),
			    (char*) str_value.ptr(),
445 446
                            key->ptr(), key->length());
      if (length >= 0)  // if we got correct data data
447
      {
448 449
        str_value.length((uint) length);
        DBUG_RETURN(&str_value);
450
      }
451 452 453 454
    }
  }
  // Bad parameters. No memory or bad data will all go here
  null_value=1;
455
  DBUG_RETURN(0);
456 457
}

458

459 460 461
void Item_func_aes_decrypt::fix_length_and_dec()
{
   max_length=args[0]->max_length;
462
   maybe_null= 1;
463
}
464 465


unknown's avatar
unknown committed
466
/**
467
  Concatenate args with the following premises:
unknown's avatar
unknown committed
468
  If only one arg (which is ok), return value of arg;
469
  Don't reallocate val_str() if not absolute necessary.
unknown's avatar
unknown committed
470 471 472 473
*/

String *Item_func_concat::val_str(String *str)
{
474
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
475 476
  String *res,*res2,*use_as_buff;
  uint i;
477
  bool is_const= 0;
unknown's avatar
unknown committed
478 479 480 481 482

  null_value=0;
  if (!(res=args[0]->val_str(str)))
    goto null;
  use_as_buff= &tmp_value;
unknown's avatar
unknown committed
483 484
  /* Item_subselect in --ps-protocol mode will state it as a non-const */
  is_const= args[0]->const_item() || !args[0]->used_tables();
unknown's avatar
unknown committed
485 486 487 488 489 490
  for (i=1 ; i < arg_count ; i++)
  {
    if (res->length() == 0)
    {
      if (!(res=args[i]->val_str(str)))
	goto null;
491 492 493 494 495 496
      /*
       CONCAT accumulates its result in the result of its the first
       non-empty argument. Because of this we need is_const to be 
       evaluated only for it.
      */
      is_const= args[i]->const_item() || !args[i]->used_tables();
unknown's avatar
unknown committed
497 498 499 500 501 502 503
    }
    else
    {
      if (!(res2=args[i]->val_str(use_as_buff)))
	goto null;
      if (res2->length() == 0)
	continue;
unknown's avatar
unknown committed
504 505
      if (res->length()+res2->length() >
	  current_thd->variables.max_allowed_packet)
506 507 508
      {
	push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			    ER_WARN_ALLOWED_PACKET_OVERFLOWED,
509 510
			    ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
			    current_thd->variables.max_allowed_packet);
511 512
	goto null;
      }
513
      if (!is_const && res->alloced_length() >= res->length()+res2->length())
unknown's avatar
unknown committed
514 515 516 517 518
      {						// Use old buffer
	res->append(*res2);
      }
      else if (str->alloced_length() >= res->length()+res2->length())
      {
519
	if (str->ptr() == res2->ptr())
unknown's avatar
unknown committed
520 521 522 523 524 525
	  str->replace(0,0,*res);
	else
	{
	  str->copy(*res);
	  str->append(*res2);
	}
526 527
        res= str;
        use_as_buff= &tmp_value;
unknown's avatar
unknown committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
      }
      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;
	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;
	use_as_buff=str;			// Put next arg here
      }
      else
      {						// Two big const strings
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
        /*
          NOTE: We should be prudent in the initial allocation unit -- the
          size of the arguments is a function of data distribution, which
          can be any. Instead of overcommitting at the first row, we grow
          the allocated amount by the factor of 2. This ensures that no
          more than 25% of memory will be overcommitted on average.
        */

        uint concat_len= res->length() + res2->length();

        if (tmp_value.alloced_length() < concat_len)
        {
          if (tmp_value.alloced_length() == 0)
          {
            if (tmp_value.alloc(concat_len))
              goto null;
          }
          else
          {
            uint new_len = max(tmp_value.alloced_length() * 2, concat_len);

            if (tmp_value.realloc(new_len))
              goto null;
          }
        }

	if (tmp_value.copy(*res) || tmp_value.append(*res2))
unknown's avatar
unknown committed
588
	  goto null;
589

unknown's avatar
unknown committed
590 591 592
	res= &tmp_value;
	use_as_buff=str;
      }
593
      is_const= 0;
unknown's avatar
unknown committed
594 595
    }
  }
596
  res->set_charset(collation.collation);
unknown's avatar
unknown committed
597 598 599 600 601 602 603 604 605 606
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_concat::fix_length_and_dec()
{
607
  ulonglong char_length= 0;
608

609
  if (agg_arg_charsets_for_string_result(collation, args, arg_count))
unknown's avatar
unknown committed
610 611
    return;

unknown's avatar
unknown committed
612
  for (uint i=0 ; i < arg_count ; i++)
613
    char_length+= args[i]->max_char_length();
614

615
  fix_char_length_ulonglong(char_length);
unknown's avatar
unknown committed
616 617
}

unknown's avatar
unknown committed
618 619
/**
  @details
unknown's avatar
unknown committed
620 621
  Function des_encrypt() by tonu@spam.ee & monty
  Works only if compiled with OpenSSL library support.
unknown's avatar
unknown committed
622 623 624 625 626
  @return
    A binary string where first character is CHAR(128 | key-number).
    If one uses a string key key_number is 127.
    Encryption result is longer than original by formula:
  @code new_length= org_length + (8-(org_length % 8))+1 @endcode
627 628
*/

629 630
String *Item_func_des_encrypt::val_str(String *str)
{
631
  DBUG_ASSERT(fixed == 1);
632
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
633
  uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
634
  DES_cblock ivec;
unknown's avatar
unknown committed
635 636
  struct st_des_keyblock keyblock;
  struct st_des_keyschedule keyschedule;
unknown's avatar
unknown committed
637 638
  const char *append_str="********";
  uint key_number, res_length, tail;
unknown's avatar
unknown committed
639
  String *res= args[0]->val_str(str);
640

unknown's avatar
unknown committed
641 642
  if ((null_value= args[0]->null_value))
    return 0;                                   // ENCRYPT(NULL) == NULL
unknown's avatar
unknown committed
643
  if ((res_length=res->length()) == 0)
644
    return make_empty_result();
unknown's avatar
unknown committed
645
  if (arg_count == 1)
unknown's avatar
unknown committed
646 647
  {
    /* Protect against someone doing FLUSH DES_KEY_FILE */
Marc Alff's avatar
Marc Alff committed
648
    mysql_mutex_lock(&LOCK_des_key_file);
unknown's avatar
unknown committed
649
    keyschedule= des_keyschedule[key_number=des_default_key];
Marc Alff's avatar
Marc Alff committed
650
    mysql_mutex_unlock(&LOCK_des_key_file);
unknown's avatar
unknown committed
651
  }
unknown's avatar
unknown committed
652
  else if (args[1]->result_type() == INT_RESULT)
unknown's avatar
unknown committed
653 654 655 656
  {
    key_number= (uint) args[1]->val_int();
    if (key_number > 9)
      goto error;
Marc Alff's avatar
Marc Alff committed
657
    mysql_mutex_lock(&LOCK_des_key_file);
unknown's avatar
unknown committed
658
    keyschedule= des_keyschedule[key_number];
Marc Alff's avatar
Marc Alff committed
659
    mysql_mutex_unlock(&LOCK_des_key_file);
660
  }
unknown's avatar
unknown committed
661 662 663 664 665
  else
  {
    String *keystr=args[1]->val_str(&tmp_value);
    if (!keystr)
      goto error;
unknown's avatar
unknown committed
666
    key_number=127;				// User key string
unknown's avatar
unknown committed
667 668

    /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */
unknown's avatar
unknown committed
669
    bzero((char*) &ivec,sizeof(ivec));
unknown's avatar
unknown committed
670 671 672
    EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
		   (uchar*) keystr->ptr(), (int) keystr->length(),
		   1, (uchar*) &keyblock,ivec);
673 674 675
    DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
    DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
    DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
unknown's avatar
unknown committed
676 677
  }

678
  /*
unknown's avatar
unknown committed
679
     The problem: DES algorithm requires original data to be in 8-bytes
680 681
     chunks. Missing bytes get filled with '*'s and result of encryption
     can be up to 8 bytes longer than original string. When decrypted,
unknown's avatar
unknown committed
682
     we do not know the size of original string :(
unknown's avatar
unknown committed
683 684
     We add one byte with value 0x1..0x8 as the last byte of the padded
     string marking change of string length.
unknown's avatar
unknown committed
685 686
  */

687
  tail= 8 - (res_length % 8);                   // 1..8 marking extra length
unknown's avatar
unknown committed
688
  res_length+=tail;
Sergey Petrunya's avatar
Sergey Petrunya committed
689 690
  if (tmp_arg.realloc(res_length))
    goto error;
691 692
  tmp_arg.length(0);
  tmp_arg.append(res->ptr(), res->length());
693
  code= ER_OUT_OF_RESOURCES;
694
  if (tmp_arg.append(append_str, tail) || tmp_value.alloc(res_length+1))
unknown's avatar
unknown committed
695
    goto error;
696 697
  tmp_arg[res_length-1]=tail;                   // save extra length
  tmp_value.realloc(res_length+1);
unknown's avatar
unknown committed
698
  tmp_value.length(res_length+1);
699
  tmp_value.set_charset(&my_charset_bin);
unknown's avatar
unknown committed
700
  tmp_value[0]=(char) (128 | key_number);
unknown's avatar
unknown committed
701
  // Real encryption
unknown's avatar
unknown committed
702
  bzero((char*) &ivec,sizeof(ivec));
703
  DES_ede3_cbc_encrypt((const uchar*) (tmp_arg.ptr()),
unknown's avatar
unknown committed
704
		       (uchar*) (tmp_value.ptr()+1),
unknown's avatar
unknown committed
705
		       res_length,
706 707 708
		       &keyschedule.ks1,
		       &keyschedule.ks2,
		       &keyschedule.ks3,
unknown's avatar
unknown committed
709 710 711 712
		       &ivec, TRUE);
  return &tmp_value;

error:
Marc Alff's avatar
Marc Alff committed
713
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,
714 715 716
                          code, ER(code),
                          "des_encrypt");
#else
Marc Alff's avatar
Marc Alff committed
717
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,
718
                      ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
Konstantin Osipov's avatar
Konstantin Osipov committed
719
                      "des_encrypt", "--with-ssl");
720
#endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
721 722 723 724
  null_value=1;
  return 0;
}

unknown's avatar
unknown committed
725

726 727
String *Item_func_des_decrypt::val_str(String *str)
{
728
  DBUG_ASSERT(fixed == 1);
729
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
730
  uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
731
  DES_cblock ivec;
unknown's avatar
unknown committed
732 733
  struct st_des_keyblock keyblock;
  struct st_des_keyschedule keyschedule;
unknown's avatar
unknown committed
734
  String *res= args[0]->val_str(str);
735
  uint length,tail;
736

737
  if ((null_value= args[0]->null_value))
unknown's avatar
unknown committed
738
    return 0;
739
  length= res->length();
unknown's avatar
unknown committed
740
  if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128))
unknown's avatar
unknown committed
741
    return res;				// Skip decryption if not encrypted
unknown's avatar
unknown committed
742

unknown's avatar
unknown committed
743
  if (arg_count == 1)			// If automatic uncompression
744
  {
unknown's avatar
unknown committed
745
    uint key_number=(uint) (*res)[0] & 127;
unknown's avatar
unknown committed
746
    // Check if automatic key and that we have privilege to uncompress using it
747 748
    if (!(current_thd->security_ctx->master_access & SUPER_ACL) ||
        key_number > 9)
unknown's avatar
unknown committed
749
      goto error;
750

Marc Alff's avatar
Marc Alff committed
751
    mysql_mutex_lock(&LOCK_des_key_file);
unknown's avatar
unknown committed
752
    keyschedule= des_keyschedule[key_number];
Marc Alff's avatar
Marc Alff committed
753
    mysql_mutex_unlock(&LOCK_des_key_file);
754
  }
unknown's avatar
unknown committed
755 756 757 758
  else
  {
    // We make good 24-byte (168 bit) key from given plaintext key with MD5
    String *keystr=args[1]->val_str(&tmp_value);
unknown's avatar
unknown committed
759
    if (!keystr)
unknown's avatar
unknown committed
760
      goto error;
unknown's avatar
unknown committed
761

unknown's avatar
unknown committed
762
    bzero((char*) &ivec,sizeof(ivec));
unknown's avatar
unknown committed
763 764 765 766
    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
767 768
    DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
    DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
unknown's avatar
unknown committed
769
    DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
unknown's avatar
unknown committed
770
  }
771
  code= ER_OUT_OF_RESOURCES;
unknown's avatar
unknown committed
772
  if (tmp_value.alloc(length-1))
unknown's avatar
unknown committed
773
    goto error;
unknown's avatar
unknown committed
774 775

  bzero((char*) &ivec,sizeof(ivec));
776
  DES_ede3_cbc_encrypt((const uchar*) res->ptr()+1,
unknown's avatar
unknown committed
777
		       (uchar*) (tmp_value.ptr()),
unknown's avatar
unknown committed
778
		       length-1,
779 780 781
		       &keyschedule.ks1,
		       &keyschedule.ks2,
		       &keyschedule.ks3,
unknown's avatar
unknown committed
782
		       &ivec, FALSE);
unknown's avatar
unknown committed
783 784
  /* Restore old length of key */
  if ((tail=(uint) (uchar) tmp_value[length-2]) > 8)
785
    goto wrong_key;				     // Wrong key
unknown's avatar
unknown committed
786
  tmp_value.length(length-1-tail);
787
  tmp_value.set_charset(&my_charset_bin);
unknown's avatar
unknown committed
788 789 790
  return &tmp_value;

error:
Marc Alff's avatar
Marc Alff committed
791
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,
792 793 794 795
                          code, ER(code),
                          "des_decrypt");
wrong_key:
#else
Marc Alff's avatar
Marc Alff committed
796
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,
797
                      ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
Konstantin Osipov's avatar
Konstantin Osipov committed
798
                      "des_decrypt", "--with-ssl");
799
#endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
800 801 802 803 804
  null_value=1;
  return 0;
}


unknown's avatar
unknown committed
805
/**
unknown's avatar
unknown committed
806 807
  concat with separator. First arg is the separator
  concat_ws takes at least two arguments.
unknown's avatar
unknown committed
808 809 810 811
*/

String *Item_func_concat_ws::val_str(String *str)
{
812
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
813
  char tmp_str_buff[10];
814
  String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
unknown's avatar
unknown committed
815 816
         *sep_str, *res, *res2,*use_as_buff;
  uint i;
817
  bool is_const= 0;
unknown's avatar
unknown committed
818 819

  null_value=0;
820
  if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
unknown's avatar
unknown committed
821 822 823
    goto null;

  use_as_buff= &tmp_value;
unknown's avatar
unknown committed
824
  str->length(0);				// QQ; Should be removed
Michael Widenius's avatar
Michael Widenius committed
825
  res=str;                                      // If 0 arg_count
unknown's avatar
unknown committed
826

827
  // Skip until non-null argument is found.
unknown's avatar
unknown committed
828
  // If not, return the empty string
829
  for (i=1; i < arg_count; i++)
830
    if ((res= args[i]->val_str(str)))
831 832
    {
      is_const= args[i]->const_item() || !args[i]->used_tables();
833
      break;
834 835
    }

unknown's avatar
unknown committed
836
  if (i ==  arg_count)
837
    return make_empty_result();
unknown's avatar
unknown committed
838 839 840

  for (i++; i < arg_count ; i++)
  {
841 842
    if (!(res2= args[i]->val_str(use_as_buff)))
      continue;					// Skip NULL
unknown's avatar
unknown committed
843 844

    if (res->length() + sep_str->length() + res2->length() >
unknown's avatar
unknown committed
845
	current_thd->variables.max_allowed_packet)
846 847 848
    {
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
849 850
			  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
			  current_thd->variables.max_allowed_packet);
851 852
      goto null;
    }
853
    if (!is_const && res->alloced_length() >=
unknown's avatar
unknown committed
854 855 856 857 858 859 860
	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())
unknown's avatar
unknown committed
861
    {
862
      /* We have room in str;  We can't get any errors here */
863 864
      if (str->ptr() == res2->ptr())
      {						// This is quite uncommon!
865 866 867 868 869 870 871 872 873
	str->replace(0,0,*sep_str);
	str->replace(0,0,*res);
      }
      else
      {
	str->copy(*res);
	str->append(*sep_str);
	str->append(*res2);
      }
unknown's avatar
unknown committed
874 875 876 877 878
      res=str;
      use_as_buff= &tmp_value;
    }
    else if (res == &tmp_value)
    {
879
      if (res->append(*sep_str) || res->append(*res2))
unknown's avatar
unknown committed
880 881
	goto null; // Must be a blob
    }
882 883 884 885 886 887 888
    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
    }
unknown's avatar
unknown committed
889
    else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
890
	     res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
unknown's avatar
unknown committed
891 892 893 894
    {
      /*
	This happens really seldom:
	In this case res2 is sub string of tmp_value.  We will
895
	now work in place in tmp_value to set it to res | sep_str | res2
unknown's avatar
unknown committed
896 897 898 899 900 901
      */
      /* 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()),
902 903
			    *res) ||
	  tmp_value.replace(res->length(),0, *sep_str))
unknown's avatar
unknown committed
904 905 906 907 908 909
	goto null;
      res= &tmp_value;
      use_as_buff=str;			// Put next arg here
    }
    else
    {						// Two big const strings
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
      /*
        NOTE: We should be prudent in the initial allocation unit -- the
        size of the arguments is a function of data distribution, which can
        be any. Instead of overcommitting at the first row, we grow the
        allocated amount by the factor of 2. This ensures that no more than
        25% of memory will be overcommitted on average.
      */

      uint concat_len= res->length() + sep_str->length() + res2->length();

      if (tmp_value.alloced_length() < concat_len)
      {
        if (tmp_value.alloced_length() == 0)
        {
          if (tmp_value.alloc(concat_len))
            goto null;
        }
        else
        {
          uint new_len = max(tmp_value.alloced_length() * 2, concat_len);

          if (tmp_value.realloc(new_len))
            goto null;
        }
      }

      if (tmp_value.copy(*res) ||
unknown's avatar
unknown committed
937 938 939 940 941
	  tmp_value.append(*sep_str) ||
	  tmp_value.append(*res2))
	goto null;
      res= &tmp_value;
      use_as_buff=str;
unknown's avatar
unknown committed
942 943
    }
  }
944
  res->set_charset(collation.collation);
unknown's avatar
unknown committed
945 946 947 948 949 950 951 952 953 954
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_concat_ws::fix_length_and_dec()
{
955
  ulonglong char_length;
956

957
  if (agg_arg_charsets_for_string_result(collation, args, arg_count))
958 959
    return;

unknown's avatar
unknown committed
960 961 962 963 964
  /*
     arg_count cannot be less than 2,
     it is done on parser level in sql_yacc.yy
     so, (arg_count - 2) is safe here.
  */
965
  char_length= (ulonglong) args[0]->max_char_length() * (arg_count - 2);
966
  for (uint i=1 ; i < arg_count ; i++)
967
    char_length+= args[i]->max_char_length();
968

969
  fix_char_length_ulonglong(char_length);
unknown's avatar
unknown committed
970 971
}

unknown's avatar
unknown committed
972 973 974

String *Item_func_reverse::val_str(String *str)
{
975
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
976
  String *res = args[0]->val_str(str);
unknown's avatar
unknown committed
977
  char *ptr, *end, *tmp;
unknown's avatar
unknown committed
978 979 980 981 982

  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())
983
    return make_empty_result();
unknown's avatar
unknown committed
984 985 986 987 988 989 990 991 992 993 994
  if (tmp_value.alloced_length() < res->length() &&
      tmp_value.realloc(res->length()))
  {
    null_value= 1;
    return 0;
  }
  tmp_value.length(res->length());
  tmp_value.set_charset(res->charset());
  ptr= (char *) res->ptr();
  end= ptr + res->length();
  tmp= (char *) tmp_value.ptr() + tmp_value.length();
unknown's avatar
unknown committed
995
#ifdef USE_MB
996
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
997 998 999 1000
  {
    register uint32 l;
    while (ptr < end)
    {
unknown's avatar
unknown committed
1001 1002 1003
      if ((l= my_ismbchar(res->charset(),ptr,end)))
      {
        tmp-= l;
1004
        DBUG_ASSERT(tmp >= tmp_value.ptr());
unknown's avatar
unknown committed
1005 1006 1007
        memcpy(tmp,ptr,l);
        ptr+= l;
      }
unknown's avatar
unknown committed
1008
      else
unknown's avatar
unknown committed
1009
        *--tmp= *ptr++;
unknown's avatar
unknown committed
1010 1011 1012 1013 1014 1015
    }
  }
  else
#endif /* USE_MB */
  {
    while (ptr < end)
unknown's avatar
unknown committed
1016
      *--tmp= *ptr++;
unknown's avatar
unknown committed
1017
  }
unknown's avatar
unknown committed
1018
  return &tmp_value;
unknown's avatar
unknown committed
1019 1020 1021 1022 1023
}


void Item_func_reverse::fix_length_and_dec()
{
1024
  agg_arg_charsets_for_string_result(collation, args, 1);
1025
  DBUG_ASSERT(collation.collation != NULL);
1026
  fix_char_length(args[0]->max_char_length());
unknown's avatar
unknown committed
1027 1028
}

unknown's avatar
unknown committed
1029 1030 1031 1032
/**
  Replace all occurences of string2 in string1 with string3.

  Don't reallocate val_str() if not needed.
unknown's avatar
unknown committed
1033

unknown's avatar
unknown committed
1034 1035 1036
  @todo
    Fix that this works with binary strings when using USE_MB 
*/
unknown's avatar
unknown committed
1037 1038 1039

String *Item_func_replace::val_str(String *str)
{
1040
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1041
  String *res,*res2,*res3;
unknown's avatar
unknown committed
1042
  int offset;
unknown's avatar
unknown committed
1043 1044 1045 1046 1047
  uint from_length,to_length;
  bool alloced=0;
#ifdef USE_MB
  const char *ptr,*end,*strend,*search,*search_end;
  register uint32 l;
1048
  bool binary_cmp;
unknown's avatar
unknown committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
#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;

1059 1060
  res->set_charset(collation.collation);

1061
#ifdef USE_MB
1062
  binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
1063 1064
#endif

unknown's avatar
unknown committed
1065 1066 1067 1068 1069 1070
  if (res2->length() == 0)
    return res;
#ifndef USE_MB
  if ((offset=res->strstr(*res2)) < 0)
    return res;
#else
unknown's avatar
unknown committed
1071
  offset=0;
1072
  if (binary_cmp && (offset=res->strstr(*res2)) < 0)
unknown's avatar
unknown committed
1073 1074 1075 1076 1077 1078 1079 1080
    return res;
#endif
  if (!(res3=args[2]->val_str(&tmp_value2)))
    goto null;
  from_length= res2->length();
  to_length=   res3->length();

#ifdef USE_MB
1081
  if (!binary_cmp)
unknown's avatar
unknown committed
1082 1083 1084 1085
  {
    search=res2->ptr();
    search_end=search+from_length;
redo:
1086
    DBUG_ASSERT(res->ptr() || !offset);
unknown's avatar
unknown committed
1087 1088
    ptr=res->ptr()+offset;
    strend=res->ptr()+res->length();
1089 1090 1091 1092 1093 1094
    /*
      In some cases val_str() can return empty string
      with ptr() == NULL and length() == 0.
      Let's check strend to avoid overflow.
    */
    end= strend ? strend - from_length + 1 : NULL;
unknown's avatar
unknown committed
1095 1096 1097 1098 1099 1100 1101
    while (ptr < end)
    {
        if (*ptr == *search)
        {
          register char *i,*j;
          i=(char*) ptr+1; j=(char*) search+1;
          while (j != search_end)
1102
            if (*i++ != *j++) goto skip;
unknown's avatar
unknown committed
1103
          offset= (int) (ptr-res->ptr());
unknown's avatar
unknown committed
1104 1105
          if (res->length()-from_length + to_length >
	      current_thd->variables.max_allowed_packet)
1106 1107 1108 1109
	  {
	    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
				ER_WARN_ALLOWED_PACKET_OVERFLOWED,
				ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1110 1111
				func_name(),
				current_thd->variables.max_allowed_packet);
1112

unknown's avatar
unknown committed
1113
            goto null;
1114
	  }
unknown's avatar
unknown committed
1115 1116 1117 1118 1119 1120
          if (!alloced)
          {
            alloced=1;
            res=copy_if_not_alloced(str,res,res->length()+to_length);
          }
          res->replace((uint) offset,from_length,*res3);
unknown's avatar
unknown committed
1121
	  offset+=(int) to_length;
unknown's avatar
unknown committed
1122 1123
          goto redo;
        }
1124
skip:
1125
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
unknown's avatar
unknown committed
1126 1127 1128 1129 1130 1131 1132
        else ++ptr;
    }
  }
  else
#endif /* USE_MB */
    do
    {
unknown's avatar
unknown committed
1133 1134
      if (res->length()-from_length + to_length >
	  current_thd->variables.max_allowed_packet)
1135 1136 1137
      {
	push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			    ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1138 1139
			    ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
			    current_thd->variables.max_allowed_packet);
unknown's avatar
unknown committed
1140
        goto null;
1141
      }
unknown's avatar
unknown committed
1142 1143 1144 1145 1146 1147 1148 1149
      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;
    }
1150
    while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
unknown's avatar
unknown committed
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_replace::fix_length_and_dec()
{
1161 1162 1163
  ulonglong char_length= (ulonglong) args[0]->max_char_length();
  int diff=(int) (args[2]->max_char_length() - args[1]->max_char_length());
  if (diff > 0 && args[1]->max_char_length())
unknown's avatar
unknown committed
1164
  {						// Calculate of maxreplaces
1165 1166
    ulonglong max_substrs= char_length / args[1]->max_char_length();
    char_length+= max_substrs * (uint) diff;
unknown's avatar
unknown committed
1167
  }
1168

1169
  if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 3))
unknown's avatar
unknown committed
1170
    return;
1171
  fix_char_length_ulonglong(char_length);
unknown's avatar
unknown committed
1172 1173 1174 1175 1176
}


String *Item_func_insert::val_str(String *str)
{
1177
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1178
  String *res,*res2;
1179
  longlong start, length;  /* must be longlong to avoid truncation */
unknown's avatar
unknown committed
1180 1181 1182 1183

  null_value=0;
  res=args[0]->val_str(str);
  res2=args[3]->val_str(&tmp_value);
1184 1185 1186
  start= args[1]->val_int() - 1;
  length= args[2]->val_int();

unknown's avatar
unknown committed
1187 1188 1189
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
      args[3]->null_value)
    goto null; /* purecov: inspected */
1190

unknown's avatar
unknown committed
1191
  if ((start < 0) || (start > res->length()))
1192
    return res;                                 // Wrong param; skip insert
unknown's avatar
unknown committed
1193 1194
  if ((length < 0) || (length > res->length()))
    length= res->length();
1195

1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
  /*
    There is one exception not handled (intentionaly) by the character set
    aggregation code. If one string is strong side and is binary, and
    another one is weak side and is a multi-byte character string,
    then we need to operate on the second string in terms on bytes when
    calling ::numchars() and ::charpos(), rather than in terms of characters.
    Lets substitute its character set to binary.
  */
  if (collation.collation == &my_charset_bin)
  {
    res->set_charset(&my_charset_bin);
    res2->set_charset(&my_charset_bin);
  }

1210
  /* start and length are now sufficiently valid to pass to charpos function */
1211 1212
   start= res->charpos((int) start);
   length= res->charpos((int) length, (uint32) start);
1213 1214

  /* Re-testing with corrected params */
1215
  if (start + 1 > res->length()) // remember, start = args[1].val_int() - 1
unknown's avatar
unknown committed
1216
    return res; /* purecov: inspected */        // Wrong param; skip insert
1217 1218 1219
  if (length > res->length() - start)
    length= res->length() - start;

unknown's avatar
unknown committed
1220 1221
  if ((ulonglong) (res->length() - length + res2->length()) >
      (ulonglong) current_thd->variables.max_allowed_packet)
1222 1223 1224
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1225 1226
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
1227 1228
    goto null;
  }
unknown's avatar
unknown committed
1229
  res=copy_if_not_alloced(str,res,res->length());
1230
  res->replace((uint32) start,(uint32) length,*res2);
unknown's avatar
unknown committed
1231 1232 1233 1234 1235 1236 1237 1238 1239
  return res;
null:
  null_value=1;
  return 0;
}


void Item_func_insert::fix_length_and_dec()
{
1240
  ulonglong char_length;
1241

1242
  // Handle character set for args[0] and args[3].
1243
  if (agg_arg_charsets_for_string_result(collation, args, 2, 3))
unknown's avatar
unknown committed
1244
    return;
1245 1246 1247
  char_length= ((ulonglong) args[0]->max_char_length() +
                (ulonglong) args[3]->max_char_length());
  fix_char_length_ulonglong(char_length);
unknown's avatar
unknown committed
1248 1249 1250
}


1251
String *Item_str_conv::val_str(String *str)
unknown's avatar
unknown committed
1252
{
1253
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1254 1255 1256 1257 1258 1259 1260
  String *res;
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  null_value=0;
1261
  if (multiply == 1)
unknown's avatar
unknown committed
1262
  {
1263
    uint len;
1264
    res= copy_if_not_alloced(&tmp_value, res, res->length());
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    len= converter(collation.collation, (char*) res->ptr(), res->length(),
                                        (char*) res->ptr(), res->length());
    DBUG_ASSERT(len <= res->length());
    res->length(len);
  }
  else
  {
    uint len= res->length() * multiply;
    tmp_value.alloc(len);
    tmp_value.set_charset(collation.collation);
    len= converter(collation.collation, (char*) res->ptr(), res->length(),
                                        (char*) tmp_value.ptr(), len);
    tmp_value.length(len);
    res= &tmp_value;
unknown's avatar
unknown committed
1279 1280 1281 1282 1283
  }
  return res;
}


1284 1285
void Item_func_lcase::fix_length_and_dec()
{
1286
  agg_arg_charsets_for_string_result(collation, args, 1);
1287
  DBUG_ASSERT(collation.collation != NULL);
1288 1289
  multiply= collation.collation->casedn_multiply;
  converter= collation.collation->cset->casedn;
1290
  fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1291 1292 1293 1294
}

void Item_func_ucase::fix_length_and_dec()
{
1295
  agg_arg_charsets_for_string_result(collation, args, 1);
1296
  DBUG_ASSERT(collation.collation != NULL);
1297 1298
  multiply= collation.collation->caseup_multiply;
  converter= collation.collation->cset->caseup;
1299
  fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1300 1301 1302
}


unknown's avatar
unknown committed
1303 1304
String *Item_func_left::val_str(String *str)
{
1305
  DBUG_ASSERT(fixed == 1);
1306 1307 1308 1309
  String *res= args[0]->val_str(str);

  /* must be longlong to avoid truncation */
  longlong length= args[1]->val_int();
1310
  uint char_pos;
unknown's avatar
unknown committed
1311

unknown's avatar
unknown committed
1312
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
1313
    return 0;
1314 1315 1316

  /* if "unsigned_flag" is set, we have a *huge* positive number. */
  if ((length <= 0) && (!args[1]->unsigned_flag))
1317
    return make_empty_result();
1318
  if ((res->length() <= (ulonglong) length) ||
1319
      (res->length() <= (char_pos= res->charpos((int) length))))
unknown's avatar
a fix  
unknown committed
1320
    return res;
1321 1322 1323

  tmp_value.set(*res, 0, char_pos);
  return &tmp_value;
unknown's avatar
unknown committed
1324 1325 1326 1327 1328
}


void Item_str_func::left_right_max_length()
{
1329
  uint32 char_length= args[0]->max_char_length();
unknown's avatar
unknown committed
1330 1331
  if (args[1]->const_item())
  {
1332
    int length= (int) args[1]->val_int();
1333
    if (args[1]->null_value || length <= 0)
1334
      char_length=0;
unknown's avatar
unknown committed
1335
    else
1336
      set_if_smaller(char_length, (uint) length);
unknown's avatar
unknown committed
1337
  }
1338
  fix_char_length(char_length);
unknown's avatar
unknown committed
1339 1340 1341 1342 1343
}


void Item_func_left::fix_length_and_dec()
{
1344
  agg_arg_charsets_for_string_result(collation, args, 1);
1345
  DBUG_ASSERT(collation.collation != NULL);
unknown's avatar
unknown committed
1346 1347 1348 1349 1350 1351
  left_right_max_length();
}


String *Item_func_right::val_str(String *str)
{
1352
  DBUG_ASSERT(fixed == 1);
1353 1354 1355
  String *res= args[0]->val_str(str);
  /* must be longlong to avoid truncation */
  longlong length= args[1]->val_int();
unknown's avatar
unknown committed
1356

unknown's avatar
unknown committed
1357
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
1358
    return 0; /* purecov: inspected */
1359 1360 1361

  /* if "unsigned_flag" is set, we have a *huge* positive number. */
  if ((length <= 0) && (!args[1]->unsigned_flag))
1362
    return make_empty_result(); /* purecov: inspected */
1363 1364

  if (res->length() <= (ulonglong) length)
unknown's avatar
unknown committed
1365
    return res; /* purecov: inspected */
unknown's avatar
unknown committed
1366

unknown's avatar
unknown committed
1367 1368
  uint start=res->numchars();
  if (start <= (uint) length)
unknown's avatar
unknown committed
1369
    return res;
unknown's avatar
unknown committed
1370
  start=res->charpos(start - (uint) length);
unknown's avatar
unknown committed
1371
  tmp_value.set(*res,start,res->length()-start);
unknown's avatar
unknown committed
1372 1373 1374 1375 1376 1377
  return &tmp_value;
}


void Item_func_right::fix_length_and_dec()
{
1378
  agg_arg_charsets_for_string_result(collation, args, 1);
1379
  DBUG_ASSERT(collation.collation != NULL);
unknown's avatar
unknown committed
1380 1381 1382 1383 1384 1385
  left_right_max_length();
}


String *Item_func_substr::val_str(String *str)
{
1386
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1387
  String *res  = args[0]->val_str(str);
1388 1389 1390 1391 1392 1393
  /* must be longlong to avoid truncation */
  longlong start= args[1]->val_int();
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Limit so that code sees out-of-bound value properly. */
  longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
  longlong tmp_length;
unknown's avatar
unknown committed
1394 1395 1396 1397

  if ((null_value=(args[0]->null_value || args[1]->null_value ||
		   (arg_count == 3 && args[2]->null_value))))
    return 0; /* purecov: inspected */
1398

1399 1400 1401
  /* Negative or zero length, will return empty string. */
  if ((arg_count == 3) && (length <= 0) && 
      (length == 0 || !args[2]->unsigned_flag))
1402
    return make_empty_result();
unknown's avatar
unknown committed
1403

1404 1405 1406 1407 1408 1409 1410
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Set here so that rest of code sees out-of-bound value as such. */
  if ((length <= 0) || (length > INT_MAX32))
    length= INT_MAX32;

  /* if "unsigned_flag" is set, we have a *huge* positive number. */
  /* Assumes that the maximum length of a String is < INT_MAX32. */
1411 1412
  if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
      (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
1413
    return make_empty_result();
unknown's avatar
unknown committed
1414

1415
  start= ((start < 0) ? res->numchars() + start : start - 1);
1416
  start= res->charpos((int) start);
1417
  if ((start < 0) || ((uint) start + 1 > res->length()))
1418
    return make_empty_result();
1419

1420
  length= res->charpos((int) length, (uint32) start);
1421 1422 1423
  tmp_length= res->length() - start;
  length= min(length, tmp_length);

1424
  if (!start && (longlong) res->length() == length)
unknown's avatar
unknown committed
1425
    return res;
1426
  tmp_value.set(*res, (uint32) start, (uint32) length);
unknown's avatar
unknown committed
1427 1428 1429 1430 1431 1432 1433 1434
  return &tmp_value;
}


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

1435
  agg_arg_charsets_for_string_result(collation, args, 1);
1436
  DBUG_ASSERT(collation.collation != NULL);
unknown's avatar
unknown committed
1437 1438
  if (args[1]->const_item())
  {
1439
    int32 start= (int32) args[1]->val_int();
1440 1441 1442
    if (args[1]->null_value)
      max_length= 0;
    else if (start < 0)
1443
      max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start);
unknown's avatar
unknown committed
1444
    else
1445
      max_length-= min((uint)(start - 1), max_length);
unknown's avatar
unknown committed
1446 1447 1448
  }
  if (arg_count == 3 && args[2]->const_item())
  {
1449
    int32 length= (int32) args[2]->val_int();
1450
    if (args[2]->null_value || length <= 0)
unknown's avatar
unknown committed
1451 1452 1453 1454
      max_length=0; /* purecov: inspected */
    else
      set_if_smaller(max_length,(uint) length);
  }
1455
  max_length*= collation.collation->mbmaxlen;
unknown's avatar
unknown committed
1456 1457 1458
}


1459 1460
void Item_func_substr_index::fix_length_and_dec()
{ 
1461
  if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 2))
unknown's avatar
unknown committed
1462
    return;
1463
  fix_char_length(args[0]->max_char_length());
1464 1465 1466
}


unknown's avatar
unknown committed
1467 1468
String *Item_func_substr_index::val_str(String *str)
{
1469
  DBUG_ASSERT(fixed == 1);
1470 1471
  char buff[MAX_FIELD_WIDTH];
  String tmp(buff,sizeof(buff),system_charset_info);
1472
  String *res= args[0]->val_str(str);
1473
  String *delimiter= args[1]->val_str(&tmp);
1474
  int32 count= (int32) args[2]->val_int();
unknown's avatar
unknown committed
1475 1476 1477 1478 1479 1480 1481 1482
  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;
1483 1484
  uint delimiter_length= delimiter->length();
  if (!res->length() || !delimiter_length || !count)
1485
    return make_empty_result();		// Wrong parameters
unknown's avatar
unknown committed
1486

1487 1488
  res->set_charset(collation.collation);

unknown's avatar
unknown committed
1489
#ifdef USE_MB
1490
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
1491
  {
1492 1493 1494 1495 1496
    const char *ptr= res->ptr();
    const char *strend= ptr+res->length();
    const char *end= strend-delimiter_length+1;
    const char *search= delimiter->ptr();
    const char *search_end= search+delimiter_length;
unknown's avatar
unknown committed
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
    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)
1508
	    if (*i++ != *j++) goto skip;
unknown's avatar
unknown committed
1509 1510
	  if (pass==0) ++n;
	  else if (!--c) break;
1511
	  ptr+= delimiter_length;
unknown's avatar
unknown committed
1512 1513
	  continue;
	}
1514
    skip:
1515
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
unknown's avatar
unknown committed
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        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 */
        {
unknown's avatar
unknown committed
1529
	  tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
unknown's avatar
unknown committed
1530 1531 1532
        }
        else /* return right part */
        {
1533
	  ptr+= delimiter_length;
unknown's avatar
unknown committed
1534
	  tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
unknown's avatar
unknown committed
1535 1536 1537 1538 1539 1540 1541 1542 1543
        }
      }
    }
  }
  else
#endif /* USE_MB */
  {
    if (count > 0)
    {					// start counting from the beginning
1544
      for (offset=0; ; offset+= delimiter_length)
unknown's avatar
unknown committed
1545
      {
1546
	if ((int) (offset= res->strstr(*delimiter, offset)) < 0)
unknown's avatar
unknown committed
1547 1548 1549 1550 1551 1552 1553 1554 1555
	  return res;			// Didn't find, return org string
	if (!--count)
	{
	  tmp_value.set(*res,0,offset);
	  break;
	}
      }
    }
    else
1556
    {
unknown's avatar
unknown committed
1557 1558 1559 1560
      /*
        Negative index, start counting at the end
      */
      for (offset=res->length(); offset ;)
unknown's avatar
unknown committed
1561
      {
unknown's avatar
unknown committed
1562 1563 1564 1565 1566
        /* 
          this call will result in finding the position pointing to one 
          address space less than where the found substring is located
          in res
        */
1567
	if ((int) (offset= res->strrstr(*delimiter, offset)) < 0)
unknown's avatar
unknown committed
1568
	  return res;			// Didn't find, return org string
unknown's avatar
unknown committed
1569 1570 1571 1572
        /*
          At this point, we've searched for the substring
          the number of times as supplied by the index value
        */
unknown's avatar
unknown committed
1573 1574
	if (!++count)
	{
1575
	  offset+= delimiter_length;
unknown's avatar
unknown committed
1576 1577 1578 1579
	  tmp_value.set(*res,offset,res->length()- offset);
	  break;
	}
      }
1580 1581
      if (count)
        return res;                     // Didn't find, return org string
unknown's avatar
unknown committed
1582 1583
    }
  }
1584 1585 1586 1587 1588 1589
  /*
    We always mark tmp_value as const so that if val_str() is called again
    on this object, we don't disrupt the contents of tmp_value when it was
    derived from another String.
  */
  tmp_value.mark_as_const();
unknown's avatar
unknown committed
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
  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)
{
1603
  DBUG_ASSERT(fixed == 1);
1604 1605 1606
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
  String tmp(buff,sizeof(buff),system_charset_info);
  String *res, *remove_str;
unknown's avatar
unknown committed
1607 1608 1609
  uint remove_length;
  LINT_INIT(remove_length);

1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
  res= args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;
  remove_str= &remove;                          /* Default value. */
  if (arg_count == 2)
  {
    remove_str= args[1]->val_str(&tmp);
    if ((null_value= args[1]->null_value))
      return 0;
  }

  if ((remove_length= remove_str->length()) == 0 ||
unknown's avatar
unknown committed
1622
      remove_length > res->length())
1623
    return non_trimmed_value(res);
unknown's avatar
unknown committed
1624

1625 1626
  ptr= (char*) res->ptr();
  end= ptr+res->length();
unknown's avatar
unknown committed
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
  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;
1637
    while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
unknown's avatar
unknown committed
1638 1639 1640 1641
      ptr+=remove_length;
    end+=remove_length;
  }
  if (ptr == res->ptr())
1642 1643
    return non_trimmed_value(res);
  return trimmed_value(res, (uint32) (ptr - res->ptr()), (uint32) (end - ptr));
unknown's avatar
unknown committed
1644 1645 1646 1647 1648
}


String *Item_func_rtrim::val_str(String *str)
{
1649
  DBUG_ASSERT(fixed == 1);
1650 1651 1652
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
  String tmp(buff, sizeof(buff), system_charset_info);
  String *res, *remove_str;
unknown's avatar
unknown committed
1653 1654 1655
  uint remove_length;
  LINT_INIT(remove_length);

1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
  res= args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;
  remove_str= &remove;                          /* Default value. */
  if (arg_count == 2)
  {
    remove_str= args[1]->val_str(&tmp);
    if ((null_value= args[1]->null_value))
      return 0;
  }

  if ((remove_length= remove_str->length()) == 0 ||
unknown's avatar
unknown committed
1668
      remove_length > res->length())
1669
    return non_trimmed_value(res);
unknown's avatar
unknown committed
1670

1671 1672
  ptr= (char*) res->ptr();
  end= ptr+res->length();
unknown's avatar
unknown committed
1673 1674 1675 1676 1677 1678 1679 1680
#ifdef USE_MB
  char *p=ptr;
  register uint32 l;
#endif
  if (remove_length == 1)
  {
    char chr=(*remove_str)[0];
#ifdef USE_MB
1681
    if (use_mb(collation.collation))
unknown's avatar
unknown committed
1682 1683 1684
    {
      while (ptr < end)
      {
1685
	if ((l= my_ismbchar(collation.collation, ptr, end))) ptr+= l, p=ptr;
unknown's avatar
unknown committed
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
	else ++ptr;
      }
      ptr=p;
    }
#endif
    while (ptr != end  && end[-1] == chr)
      end--;
  }
  else
  {
    const char *r_ptr=remove_str->ptr();
#ifdef USE_MB
1698
    if (use_mb(collation.collation))
unknown's avatar
unknown committed
1699 1700 1701 1702
    {
  loop:
      while (ptr + remove_length < end)
      {
1703
	if ((l= my_ismbchar(collation.collation, ptr, end))) ptr+= l;
unknown's avatar
unknown committed
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
	else ++ptr;
      }
      if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
      {
	end-=remove_length;
	ptr=p;
	goto loop;
      }
    }
    else
#endif /* USE_MB */
    {
1716 1717
      while (ptr + remove_length <= end &&
	     !memcmp(end-remove_length, r_ptr, remove_length))
unknown's avatar
unknown committed
1718 1719 1720 1721
	end-=remove_length;
    }
  }
  if (end == res->ptr()+res->length())
1722 1723
    return non_trimmed_value(res);
  return trimmed_value(res, 0, (uint32) (end - res->ptr()));
unknown's avatar
unknown committed
1724 1725 1726 1727 1728
}


String *Item_func_trim::val_str(String *str)
{
1729
  DBUG_ASSERT(fixed == 1);
1730 1731 1732 1733
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
  const char *r_ptr;
  String tmp(buff, sizeof(buff), system_charset_info);
  String *res, *remove_str;
unknown's avatar
unknown committed
1734 1735
  uint remove_length;
  LINT_INIT(remove_length);
unknown's avatar
unknown committed
1736

1737 1738 1739 1740
  res= args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;
  remove_str= &remove;                          /* Default value. */
unknown's avatar
unknown committed
1741 1742 1743 1744 1745 1746
  if (arg_count == 2)
  {
    remove_str= args[1]->val_str(&tmp);
    if ((null_value= args[1]->null_value))
      return 0;
  }
unknown's avatar
unknown committed
1747

1748
  if ((remove_length= remove_str->length()) == 0 ||
unknown's avatar
unknown committed
1749
      remove_length > res->length())
1750
    return non_trimmed_value(res);
unknown's avatar
unknown committed
1751

1752 1753 1754
  ptr= (char*) res->ptr();
  end= ptr+res->length();
  r_ptr= remove_str->ptr();
1755 1756
  while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
    ptr+=remove_length;
unknown's avatar
unknown committed
1757
#ifdef USE_MB
1758
  if (use_mb(collation.collation))
unknown's avatar
unknown committed
1759 1760 1761 1762 1763 1764
  {
    char *p=ptr;
    register uint32 l;
 loop:
    while (ptr + remove_length < end)
    {
1765
      if ((l= my_ismbchar(collation.collation, ptr, end)))
1766 1767 1768
        ptr+= l;
      else
        ++ptr;
unknown's avatar
unknown committed
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    }
    if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
    {
      end-=remove_length;
      ptr=p;
      goto loop;
    }
    ptr=p;
  }
  else
#endif /* USE_MB */
  {
unknown's avatar
unknown committed
1781
    while (ptr + remove_length <= end &&
unknown's avatar
unknown committed
1782 1783 1784 1785
	   !memcmp(end-remove_length,r_ptr,remove_length))
      end-=remove_length;
  }
  if (ptr == res->ptr() && end == ptr+res->length())
1786 1787
    return non_trimmed_value(res);
  return trimmed_value(res, (uint32) (ptr - res->ptr()), (uint32) (end - ptr));
unknown's avatar
unknown committed
1788 1789
}

1790 1791 1792 1793
void Item_func_trim::fix_length_and_dec()
{
  if (arg_count == 1)
  {
1794
    agg_arg_charsets_for_string_result(collation, args, 1);
1795
    DBUG_ASSERT(collation.collation != NULL);
1796
    remove.set_charset(collation.collation);
1797 1798 1799 1800
    remove.set_ascii(" ",1);
  }
  else
  {
1801 1802
    // Handle character set for args[1] and args[0].
    // Note that we pass args[1] as the first item, and args[0] as the second.
1803 1804
    if (agg_arg_charsets_for_string_result_with_comparison(collation,
                                                           &args[1], 2, -1))
unknown's avatar
unknown committed
1805
      return;
1806
  }
1807
  fix_char_length(args[0]->max_char_length());
1808 1809
}

1810
void Item_func_trim::print(String *str, enum_query_type query_type)
1811 1812 1813
{
  if (arg_count == 1)
  {
1814
    Item_func::print(str, query_type);
1815 1816 1817 1818 1819 1820
    return;
  }
  str->append(Item_func_trim::func_name());
  str->append('(');
  str->append(mode_name());
  str->append(' ');
1821
  args[1]->print(str, query_type);
1822
  str->append(STRING_WITH_LEN(" from "));
1823
  args[0]->print(str, query_type);
1824 1825 1826
  str->append(')');
}

1827

1828
/* Item_func_password */
unknown's avatar
unknown committed
1829

1830
String *Item_func_password::val_str_ascii(String *str)
unknown's avatar
unknown committed
1831
{
1832
  DBUG_ASSERT(fixed == 1);
1833
  String *res= args[0]->val_str(str); 
unknown's avatar
unknown committed
1834 1835
  if ((null_value=args[0]->null_value))
    return 0;
1836
  if (res->length() == 0)
1837
    return make_empty_result();
1838
  my_make_scrambled_password(tmp_value, res->ptr(), res->length());
1839
  str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, &my_charset_latin1);
1840
  return str;
unknown's avatar
unknown committed
1841 1842
}

1843 1844
char *Item_func_password::alloc(THD *thd, const char *password,
                                size_t pass_len)
unknown's avatar
unknown committed
1845 1846 1847
{
  char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH+1);
  if (buff)
1848
    my_make_scrambled_password(buff, password, pass_len);
unknown's avatar
unknown committed
1849 1850 1851
  return buff;
}

1852 1853
/* Item_func_old_password */

1854
String *Item_func_old_password::val_str_ascii(String *str)
1855
{
1856
  DBUG_ASSERT(fixed == 1);
1857
  String *res= args[0]->val_str(str);
1858 1859 1860
  if ((null_value=args[0]->null_value))
    return 0;
  if (res->length() == 0)
1861
    return make_empty_result();
1862
  my_make_scrambled_password_323(tmp_value, res->ptr(), res->length());
1863
  str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, &my_charset_latin1);
1864 1865 1866
  return str;
}

1867 1868
char *Item_func_old_password::alloc(THD *thd, const char *password,
                                    size_t pass_len)
unknown's avatar
unknown committed
1869 1870 1871
{
  char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1);
  if (buff)
1872
    my_make_scrambled_password_323(buff, password, pass_len);
unknown's avatar
unknown committed
1873 1874
  return buff;
}
1875 1876


unknown's avatar
unknown committed
1877
#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
unknown's avatar
unknown committed
1878 1879 1880

String *Item_func_encrypt::val_str(String *str)
{
1881
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1882 1883 1884 1885 1886 1887 1888
  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)
1889
    return make_empty_result();
unknown's avatar
unknown committed
1890 1891 1892
  if (arg_count == 1)
  {					// generate random salt
    time_t timestamp=current_thd->query_start();
unknown's avatar
unknown committed
1893 1894
    salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
    salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
unknown's avatar
unknown committed
1895 1896 1897 1898 1899 1900 1901 1902
    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;
1903
    salt_ptr= salt_str->c_ptr_safe();
unknown's avatar
unknown committed
1904
  }
Marc Alff's avatar
Marc Alff committed
1905
  mysql_mutex_lock(&LOCK_crypt);
1906
  char *tmp= crypt(res->c_ptr_safe(),salt_ptr);
1907 1908
  if (!tmp)
  {
Marc Alff's avatar
Marc Alff committed
1909
    mysql_mutex_unlock(&LOCK_crypt);
1910 1911 1912
    null_value= 1;
    return 0;
  }
1913
  str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
unknown's avatar
unknown committed
1914
  str->copy();
Marc Alff's avatar
Marc Alff committed
1915
  mysql_mutex_unlock(&LOCK_crypt);
unknown's avatar
unknown committed
1916 1917 1918 1919 1920 1921 1922
  return str;
#else
  null_value=1;
  return 0;
#endif	/* HAVE_CRYPT */
}

1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
bool Item_func_encode::seed()
{
  char buf[80];
  ulong rand_nr[2];
  String *key, tmp(buf, sizeof(buf), system_charset_info);

  if (!(key= args[1]->val_str(&tmp)))
    return TRUE;

  hash_password(rand_nr, key->ptr(), key->length());
  sql_crypt.init(rand_nr);

  return FALSE;
}

unknown's avatar
unknown committed
1938 1939 1940
void Item_func_encode::fix_length_and_dec()
{
  max_length=args[0]->max_length;
1941
  maybe_null=args[0]->maybe_null || args[1]->maybe_null;
1942
  collation.set(&my_charset_bin);
1943 1944 1945
  /* Precompute the seed state if the item is constant. */
  seeded= args[1]->const_item() &&
          (args[1]->result_type() == STRING_RESULT) && !seed();
unknown's avatar
unknown committed
1946 1947 1948 1949 1950
}

String *Item_func_encode::val_str(String *str)
{
  String *res;
1951 1952
  DBUG_ASSERT(fixed == 1);

unknown's avatar
unknown committed
1953 1954
  if (!(res=args[0]->val_str(str)))
  {
1955 1956
    null_value= 1;
    return NULL;
unknown's avatar
unknown committed
1957
  }
1958

1959
  if (!seeded && seed())
1960
  {
1961 1962
    null_value= 1;
    return NULL;
1963 1964
  }

1965 1966
  null_value= 0;
  res= copy_if_not_alloced(str, res, res->length());
Davi Arnaut's avatar
Davi Arnaut committed
1967
  crypto_transform(res);
1968 1969
  sql_crypt.reinit();

unknown's avatar
unknown committed
1970 1971 1972
  return res;
}

Davi Arnaut's avatar
Davi Arnaut committed
1973
void Item_func_encode::crypto_transform(String *res)
unknown's avatar
unknown committed
1974
{
1975 1976 1977
  sql_crypt.encode((char*) res->ptr(),res->length());
  res->set_charset(&my_charset_bin);
}
1978

Davi Arnaut's avatar
Davi Arnaut committed
1979
void Item_func_decode::crypto_transform(String *res)
1980
{
unknown's avatar
unknown committed
1981 1982 1983 1984
  sql_crypt.decode((char*) res->ptr(),res->length());
}


1985 1986 1987 1988 1989
Item *Item_func_sysconst::safe_charset_converter(CHARSET_INFO *tocs)
{
  Item_string *conv;
  uint conv_errors;
  String tmp, cstr, *ostr= val_str(&tmp);
1990 1991 1992 1993 1994 1995
  if (null_value)
  {
    Item *null_item= new Item_null((char *) fully_qualified_func_name());
    null_item->collation.set (tocs);
    return null_item;
  }
1996
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
1997 1998 1999 2000 2001
  if (conv_errors ||
      !(conv= new Item_static_string_func(fully_qualified_func_name(),
                                          cstr.ptr(), cstr.length(),
                                          cstr.charset(),
                                          collation.derivation)))
2002 2003 2004 2005
  {
    return NULL;
  }
  conv->str_value.copy();
unknown's avatar
unknown committed
2006
  conv->str_value.mark_as_const();
2007 2008 2009 2010
  return conv;
}


unknown's avatar
unknown committed
2011 2012
String *Item_func_database::val_str(String *str)
{
2013
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2014
  THD *thd= current_thd;
unknown's avatar
unknown committed
2015
  if (thd->db == NULL)
2016
  {
2017 2018
    null_value= 1;
    return 0;
2019
  }
unknown's avatar
unknown committed
2020
  else
unknown's avatar
unknown committed
2021
    str->copy(thd->db, thd->db_length, system_charset_info);
unknown's avatar
unknown committed
2022 2023 2024
  return str;
}

unknown's avatar
unknown committed
2025

unknown's avatar
unknown committed
2026
/**
2027 2028 2029
  @note USER() is replicated correctly if binlog_format=ROW or (as of
  BUG#28086) binlog_format=MIXED, but is incorrectly replicated to ''
  if binlog_format=STATEMENT.
2030 2031
*/
bool Item_func_user::init(const char *user, const char *host)
unknown's avatar
unknown committed
2032
{
2033
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2034

2035 2036
  // For system threads (e.g. replication SQL thread) user may be empty
  if (user)
2037
  {
2038
    CHARSET_INFO *cs= str_value.charset();
2039
    size_t res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
2040

2041
    if (str_value.alloc((uint) res_length))
2042 2043 2044 2045
    {
      null_value=1;
      return TRUE;
    }
2046

2047
    res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), (uint) res_length,
2048
                                  "%s@%s", user, host);
2049
    str_value.length((uint) res_length);
2050
    str_value.mark_as_const();
2051
  }
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
  return FALSE;
}


bool Item_func_user::fix_fields(THD *thd, Item **ref)
{
  return (Item_func_sysconst::fix_fields(thd, ref) ||
          init(thd->main_security_ctx.user,
               thd->main_security_ctx.host_or_ip));
}


bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
{
  if (Item_func_sysconst::fix_fields(thd, ref))
    return TRUE;

2069 2070 2071
  Security_context *ctx=
#ifndef NO_EMBEDDED_ACCESS_CHECKS
                         (context->security_ctx
2072
                          ? context->security_ctx : thd->security_ctx);
2073 2074 2075
#else
                         thd->security_ctx;
#endif /*NO_EMBEDDED_ACCESS_CHECKS*/
2076
  return init(ctx->priv_user, ctx->priv_host);
unknown's avatar
unknown committed
2077 2078
}

2079

unknown's avatar
unknown committed
2080 2081
void Item_func_soundex::fix_length_and_dec()
{
2082
  uint32 char_length= args[0]->max_char_length();
2083
  agg_arg_charsets_for_string_result(collation, args, 1);
2084 2085 2086
  DBUG_ASSERT(collation.collation != NULL);
  set_if_bigger(char_length, 4);
  fix_char_length(char_length);
2087
  tmp_value.set_charset(collation.collation);
unknown's avatar
unknown committed
2088 2089 2090
}


unknown's avatar
unknown committed
2091
/**
2092 2093 2094 2095
  If alpha, map input letter to soundex code.
  If not alpha and remove_garbage is set then skip to next char
  else return 0
*/
unknown's avatar
unknown committed
2096

2097
static int soundex_toupper(int ch)
unknown's avatar
unknown committed
2098
{
2099 2100 2101
  return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch;
}

2102 2103

static char get_scode(int wc)
2104
{
2105
  int ch= soundex_toupper(wc);
unknown's avatar
unknown committed
2106 2107 2108 2109 2110 2111 2112 2113 2114
  if (ch < 'A' || ch > 'Z')
  {
					// Thread extended alfa (country spec)
    return '0';				// as vokal
  }
  return(soundex_map[ch-'A']);
}


2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
static bool my_uni_isalpha(int wc)
{
  /*
    Return true for all Basic Latin letters: a..z A..Z.
    Return true for all Unicode characters with code higher than U+00C0:
    - characters between 'z' and U+00C0 are controls and punctuations.
    - "U+00C0 LATIN CAPITAL LETTER A WITH GRAVE" is the first letter after 'z'.
  */
  return (wc >= 'a' && wc <= 'z') ||
         (wc >= 'A' && wc <= 'Z') ||
         (wc >= 0xC0);
}


unknown's avatar
unknown committed
2129 2130
String *Item_func_soundex::val_str(String *str)
{
2131
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2132 2133
  String *res  =args[0]->val_str(str);
  char last_ch,ch;
2134
  CHARSET_INFO *cs= collation.collation;
2135 2136 2137
  my_wc_t wc;
  uint nchars;
  int rc;
unknown's avatar
unknown committed
2138

2139
  if ((null_value= args[0]->null_value))
unknown's avatar
unknown committed
2140 2141
    return 0; /* purecov: inspected */

2142
  if (tmp_value.alloc(max(res->length(), 4 * cs->mbminlen)))
unknown's avatar
unknown committed
2143
    return str; /* purecov: inspected */
unknown's avatar
unknown committed
2144
  char *to= (char *) tmp_value.ptr();
2145 2146
  char *to_end= to + tmp_value.alloced_length();
  char *from= (char *) res->ptr(), *end= from + res->length();
unknown's avatar
unknown committed
2147
  
2148
  for ( ; ; ) /* Skip pre-space */
unknown's avatar
unknown committed
2149
  {
2150
    if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2151
      return make_empty_result(); /* EOL or invalid byte sequence */
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
    
    if (rc == 1 && cs->ctype)
    {
      /* Single byte letter found */
      if (my_isalpha(cs, *from))
      {
        last_ch= get_scode(*from);       // Code of the first letter
        *to++= soundex_toupper(*from++); // Copy first letter
        break;
      }
      from++;
    }
    else
    {
      from+= rc;
      if (my_uni_isalpha(wc))
      {
        /* Multibyte letter found */
        wc= soundex_toupper(wc);
        last_ch= get_scode(wc);     // Code of the first letter
        if ((rc= cs->cset->wc_mb(cs, wc, (uchar*) to, (uchar*) to_end)) <= 0)
        {
          /* Extra safety - should not really happen */
          DBUG_ASSERT(false);
2176
          return make_empty_result();
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
        }
        to+= rc;
        break;
      }
    }
  }
  
  /*
     last_ch is now set to the first 'double-letter' check.
     loop on input letters until end of input
  */
  for (nchars= 1 ; ; )
  {
    if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
      break; /* EOL or invalid byte sequence */

    if (rc == 1 && cs->ctype)
    {
      if (!my_isalpha(cs, *from++))
        continue;
    }
    else
    {
      from+= rc;
      if (!my_uni_isalpha(wc))
        continue;
    }
    
    ch= get_scode(wc);
unknown's avatar
unknown committed
2206 2207
    if ((ch != '0') && (ch != last_ch)) // if not skipped or double
    {
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
      // letter, copy to output
      if ((rc= cs->cset->wc_mb(cs, (my_wc_t) ch,
                               (uchar*) to, (uchar*) to_end)) <= 0)
      {
        // Extra safety - should not really happen
        DBUG_ASSERT(false);
        break;
      }
      to+= rc;
      nchars++;
      last_ch= ch;  // save code of last input letter
    }               // for next double-letter check
unknown's avatar
unknown committed
2220
  }
2221 2222 2223 2224 2225 2226 2227 2228 2229
  
  /* Pad up to 4 characters with DIGIT ZERO, if the string is shorter */
  if (nchars < 4) 
  {
    uint nbytes= (4 - nchars) * cs->mbminlen;
    cs->cset->fill(cs, to, nbytes, '0');
    to+= nbytes;
  }

unknown's avatar
unknown committed
2230 2231
  tmp_value.length((uint) (to-tmp_value.ptr()));
  return &tmp_value;
unknown's avatar
unknown committed
2232 2233 2234
}


unknown's avatar
unknown committed
2235 2236 2237 2238
/**
  Change a number to format '3,333,333,333.000'.

  This should be 'internationalized' sometimes.
unknown's avatar
unknown committed
2239 2240
*/

2241 2242
const int FORMAT_MAX_DECIMALS= 30;

2243 2244

MY_LOCALE *Item_func_format::get_locale(Item *item)
2245
{
2246
  DBUG_ASSERT(arg_count == 3);
2247
  String tmp, *locale_name= args[2]->val_str_ascii(&tmp);
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
  MY_LOCALE *lc;
  if (!locale_name ||
      !(lc= my_locale_by_name(locale_name->c_ptr_safe())))
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_UNKNOWN_LOCALE,
                        ER(ER_UNKNOWN_LOCALE),
                        locale_name ? locale_name->c_ptr_safe() : "NULL");
    lc= &my_locale_en_US;
  }
  return lc;
2259 2260 2261
}

void Item_func_format::fix_length_and_dec()
unknown's avatar
unknown committed
2262
{
2263 2264
  uint32 char_length= args[0]->max_char_length();
  uint32 max_sep_count= (char_length / 3) + (decimals ? 1 : 0) + /*sign*/1;
2265
  collation.set(default_charset());
2266
  fix_char_length(char_length + max_sep_count + decimals);
2267 2268 2269 2270
  if (arg_count == 3)
    locale= args[2]->basic_const_item() ? get_locale(args[2]) : NULL;
  else
    locale= &my_locale_en_US; /* Two arguments */
unknown's avatar
unknown committed
2271 2272 2273
}


unknown's avatar
unknown committed
2274 2275 2276
/**
  @todo
  This needs to be fixed for multi-byte character set where numbers
unknown's avatar
unknown committed
2277 2278 2279
  are stored in more than one byte
*/

2280
String *Item_func_format::val_str_ascii(String *str)
unknown's avatar
unknown committed
2281
{
2282 2283 2284 2285 2286
  uint32 str_length;
  /* Number of decimal digits */
  int dec;
  /* Number of characters used to represent the decimals, including '.' */
  uint32 dec_length;
2287
  MY_LOCALE *lc;
2288
  DBUG_ASSERT(fixed == 1);
2289

unknown's avatar
unknown committed
2290
  dec= (int) args[1]->val_int();
2291 2292 2293 2294 2295 2296
  if (args[1]->null_value)
  {
    null_value=1;
    return NULL;
  }

2297 2298
  lc= locale ? locale : get_locale(args[2]);

2299 2300 2301
  dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
  dec_length= dec ? dec+1 : 0;
  null_value=0;
2302

2303 2304 2305 2306 2307
  if (args[0]->result_type() == DECIMAL_RESULT ||
      args[0]->result_type() == INT_RESULT)
  {
    my_decimal dec_val, rnd_dec, *res;
    res= args[0]->val_decimal(&dec_val);
2308 2309
    if ((null_value=args[0]->null_value))
      return 0; /* purecov: inspected */
2310
    my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
2311 2312 2313 2314 2315 2316 2317 2318
    my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
    str_length= str->length();
  }
  else
  {
    double nr= args[0]->val_real();
    if ((null_value=args[0]->null_value))
      return 0; /* purecov: inspected */
2319
    nr= my_double_round(nr, (longlong) dec, FALSE, FALSE);
2320
    str->set_real(nr, dec, &my_charset_numeric);
2321
    if (isnan(nr) || my_isinf(nr))
2322 2323 2324
      return str;
    str_length=str->length();
  }
2325 2326 2327
  /* We need this test to handle 'nan' and short values */
  if (lc->grouping[0] > 0 &&
      str_length >= dec_length + 1 + lc->grouping[0])
unknown's avatar
unknown committed
2328
  {
2329 2330
    /* We need space for ',' between each group of digits as well. */
    char buf[2 * FLOATING_POINT_BUFFER];
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
    int count;
    const char *grouping= lc->grouping;
    char sign_length= *str->ptr() == '-' ? 1 : 0;
    const char *src= str->ptr() + str_length - dec_length - 1;
    const char *src_begin= str->ptr() + sign_length;
    char *dst= buf + sizeof(buf);
    
    /* Put the fractional part */
    if (dec)
    {
      dst-= (dec + 1);
      *dst= lc->decimal_point;
      memcpy(dst + 1, src + 2, dec);
    }
    
    /* Put the integer part with grouping */
    for (count= *grouping; src >= src_begin; count--)
unknown's avatar
unknown committed
2348
    {
2349 2350 2351 2352 2353
      /*
        When *grouping==0x80 (which means "end of grouping")
        count will be initialized to -1 and
        we'll never get into this "if" anymore.
      */
2354
      if (count == 0)
2355 2356 2357 2358 2359 2360 2361 2362
      {
        *--dst= lc->thousand_sep;
        if (grouping[1])
          grouping++;
        count= *grouping;
      }
      DBUG_ASSERT(dst > buf);
      *--dst= *src--;
unknown's avatar
unknown committed
2363
    }
2364 2365 2366 2367 2368 2369
    
    if (sign_length) /* Put '-' */
      *--dst= *str->ptr();
    
    /* Put the rest of the integer part without grouping */
    str->copy(dst, buf + sizeof(buf) - dst, &my_charset_latin1);
unknown's avatar
unknown committed
2370
  }
2371 2372 2373 2374 2375 2376
  else if (dec_length && lc->decimal_point != '.')
  {
    /*
      For short values without thousands (<1000)
      replace decimal point to localized value.
    */
2377
    DBUG_ASSERT(dec_length <= str_length);
2378 2379
    ((char*) str->ptr())[str_length - dec_length]= lc->decimal_point;
  }
unknown's avatar
unknown committed
2380 2381 2382 2383
  return str;
}


2384
void Item_func_format::print(String *str, enum_query_type query_type)
2385
{
2386
  str->append(STRING_WITH_LEN("format("));
2387
  args[0]->print(str, query_type);
2388
  str->append(',');
2389
  args[1]->print(str, query_type);
2390 2391 2392 2393 2394
  if(arg_count > 2)
  {
    str->append(',');
    args[2]->print(str,query_type);
  }
2395 2396 2397
  str->append(')');
}

unknown's avatar
unknown committed
2398 2399
void Item_func_elt::fix_length_and_dec()
{
2400
  uint32 char_length= 0;
unknown's avatar
unknown committed
2401
  decimals=0;
2402

2403
  if (agg_arg_charsets_for_string_result(collation, args + 1, arg_count - 1))
unknown's avatar
unknown committed
2404 2405
    return;

2406
  for (uint i= 1 ; i < arg_count ; i++)
unknown's avatar
unknown committed
2407
  {
2408
    set_if_bigger(char_length, args[i]->max_char_length());
unknown's avatar
unknown committed
2409 2410
    set_if_bigger(decimals,args[i]->decimals);
  }
2411
  fix_char_length(char_length);
2412
  maybe_null=1;					// NULL if wrong first arg
unknown's avatar
unknown committed
2413 2414 2415
}


2416
double Item_func_elt::val_real()
unknown's avatar
unknown committed
2417
{
2418
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2419
  uint tmp;
2420
  null_value=1;
2421
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
unknown's avatar
unknown committed
2422
    return 0.0;
2423
  double result= args[tmp]->val_real();
unknown's avatar
unknown committed
2424
  null_value= args[tmp]->null_value;
2425
  return result;
unknown's avatar
unknown committed
2426 2427
}

unknown's avatar
unknown committed
2428

unknown's avatar
unknown committed
2429 2430
longlong Item_func_elt::val_int()
{
2431
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2432
  uint tmp;
2433
  null_value=1;
2434
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
unknown's avatar
unknown committed
2435
    return 0;
unknown's avatar
unknown committed
2436 2437 2438

  longlong result= args[tmp]->val_int();
  null_value= args[tmp]->null_value;
2439
  return result;
unknown's avatar
unknown committed
2440 2441
}

unknown's avatar
unknown committed
2442

unknown's avatar
unknown committed
2443 2444
String *Item_func_elt::val_str(String *str)
{
2445
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2446
  uint tmp;
2447
  null_value=1;
2448
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
unknown's avatar
unknown committed
2449
    return NULL;
2450

unknown's avatar
unknown committed
2451 2452 2453 2454
  String *result= args[tmp]->val_str(str);
  if (result)
    result->set_charset(collation.collation);
  null_value= args[tmp]->null_value;
2455
  return result;
unknown's avatar
unknown committed
2456 2457 2458 2459 2460
}


void Item_func_make_set::fix_length_and_dec()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
2461
  uint32 char_length= arg_count - 2; /* Separators */
unknown's avatar
unknown committed
2462

Sergei Golubchik's avatar
Sergei Golubchik committed
2463
  if (agg_arg_charsets_for_string_result(collation, args + 1, arg_count - 1))
unknown's avatar
unknown committed
2464 2465
    return;
  
2466
  for (uint i=1 ; i < arg_count ; i++)
2467 2468
    char_length+= args[i]->max_char_length();
  fix_char_length(char_length);
unknown's avatar
unknown committed
2469 2470 2471 2472 2473
}


String *Item_func_make_set::val_str(String *str)
{
2474
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2475 2476
  ulonglong bits;
  bool first_found=0;
2477
  Item **ptr=args+1;
2478
  String *result= make_empty_result();
unknown's avatar
unknown committed
2479

2480 2481
  bits=args[0]->val_int();
  if ((null_value=args[0]->null_value))
unknown's avatar
unknown committed
2482 2483
    return NULL;

2484 2485
  if (arg_count < 65)
    bits &= ((ulonglong) 1 << (arg_count-1))-1;
unknown's avatar
unknown committed
2486 2487 2488 2489 2490 2491

  for (; bits; bits >>= 1, ptr++)
  {
    if (bits & 1)
    {
      String *res= (*ptr)->val_str(str);
unknown's avatar
unknown committed
2492
      if (res)					// Skip nulls
unknown's avatar
unknown committed
2493 2494 2495 2496 2497 2498 2499 2500 2501
      {
	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'
2502
              return make_empty_result();
unknown's avatar
unknown committed
2503 2504 2505 2506 2507 2508 2509 2510 2511
	    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))
2512
              return make_empty_result();
unknown's avatar
unknown committed
2513 2514
	    result= &tmp_str;
	  }
2515
	  if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
2516
            return make_empty_result();
unknown's avatar
unknown committed
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
	}
      }
    }
  }
  return result;
}


String *Item_func_char::val_str(String *str)
{
2527
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2528
  str->length(0);
2529
  str->set_charset(collation.collation);
unknown's avatar
unknown committed
2530 2531 2532 2533
  for (uint i=0 ; i < arg_count ; i++)
  {
    int32 num=(int32) args[i]->val_int();
    if (!args[i]->null_value)
2534
    {
Alexander Barkov's avatar
Alexander Barkov committed
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
      char tmp[4];
      if (num & 0xFF000000L)
      {
        mi_int4store(tmp, num);
        str->append(tmp, 4, &my_charset_bin);
      }
      else if (num & 0xFF0000L)
      {
        mi_int3store(tmp, num);
        str->append(tmp, 3, &my_charset_bin);
      }
      else if (num & 0xFF00L)
      {
        mi_int2store(tmp, num);
        str->append(tmp, 2, &my_charset_bin);
      }
      else
      {
        tmp[0]= (char) num;
        str->append(tmp, 1, &my_charset_bin);
unknown's avatar
unknown committed
2555
      }
2556
    }
unknown's avatar
unknown committed
2557 2558
  }
  str->realloc(str->length());			// Add end 0 (for Purify)
2559
  return check_well_formed_result(str);
unknown's avatar
unknown committed
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
}


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;
    }
2574 2575 2576 2577 2578
    if (tmp_value->alloc(length))
      return 0;
    (void) tmp_value->copy(*res);
    tmp_value->length(length);
    return tmp_value;
unknown's avatar
unknown committed
2579 2580 2581 2582 2583 2584 2585 2586
  }
  res->length(length);
  return res;
}


void Item_func_repeat::fix_length_and_dec()
{
2587
  agg_arg_charsets_for_string_result(collation, args, 1);
2588
  DBUG_ASSERT(collation.collation != NULL);
unknown's avatar
unknown committed
2589 2590
  if (args[1]->const_item())
  {
2591 2592 2593 2594 2595
    /* must be longlong to avoid truncation */
    longlong count= args[1]->val_int();

    /* Assumes that the maximum length of a String is < INT_MAX32. */
    /* Set here so that rest of code sees out-of-bound value as such. */
2596 2597 2598
    if (args[1]->null_value)
      count= 0;
    else if (count > INT_MAX32)
2599 2600
      count= INT_MAX32;

2601 2602
    ulonglong char_length= (ulonglong) args[0]->max_char_length() * count;
    fix_char_length_ulonglong(char_length);
unknown's avatar
unknown committed
2603 2604 2605
  }
  else
  {
2606
    max_length= MAX_BLOB_WIDTH;
2607
    maybe_null= 1;
unknown's avatar
unknown committed
2608 2609 2610
  }
}

unknown's avatar
unknown committed
2611 2612 2613
/**
  Item_func_repeat::str is carefully written to avoid reallocs
  as much as possible at the cost of a local buffer
unknown's avatar
unknown committed
2614 2615 2616 2617
*/

String *Item_func_repeat::val_str(String *str)
{
2618
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2619 2620
  uint length,tot_length;
  char *to;
2621
  /* must be longlong to avoid truncation */
2622
  longlong count= args[1]->val_int();
2623 2624
  String *res= args[0]->val_str(str);

unknown's avatar
unknown committed
2625 2626
  if (args[0]->null_value || args[1]->null_value)
    goto err;				// string and/or delim are null
2627
  null_value= 0;
2628

2629
  if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
2630
    return make_empty_result();
2631

2632 2633 2634 2635
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Bounds check on count:  If this is triggered, we will error. */
  if ((ulonglong) count > INT_MAX32)
    count= INT_MAX32;
unknown's avatar
unknown committed
2636 2637 2638
  if (count == 1)			// To avoid reallocs
    return res;
  length=res->length();
unknown's avatar
unknown committed
2639
  // Safe length check
2640
  if (length > current_thd->variables.max_allowed_packet / (uint) count)
2641 2642 2643
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2644 2645
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
2646 2647
    goto err;
  }
unknown's avatar
unknown committed
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
  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()
{
2668
  // Handle character set for args[0] and args[2].
2669
  if (agg_arg_charsets_for_string_result(collation, &args[0], 2, 2))
2670
    return;
unknown's avatar
unknown committed
2671 2672
  if (args[1]->const_item())
  {
2673 2674 2675 2676
    ulonglong char_length= (ulonglong) args[1]->val_int();
    DBUG_ASSERT(collation.collation->mbmaxlen > 0);
    /* Assumes that the maximum length of a String is < INT_MAX32. */
    /* Set here so that rest of code sees out-of-bound value as such. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2677 2678 2679
    if (args[1]->null_value)
      char_length= 0;
    else if (char_length > INT_MAX32)
2680 2681
      char_length= INT_MAX32;
    fix_char_length_ulonglong(char_length);
unknown's avatar
unknown committed
2682 2683 2684
  }
  else
  {
2685
    max_length= MAX_BLOB_WIDTH;
2686
    maybe_null= 1;
unknown's avatar
unknown committed
2687 2688 2689 2690 2691 2692
  }
}


String *Item_func_rpad::val_str(String *str)
{
2693
  DBUG_ASSERT(fixed == 1);
2694
  uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
unknown's avatar
unknown committed
2695 2696
  char *to;
  const char *ptr_pad;
2697 2698 2699 2700 2701 2702
  /* must be longlong to avoid truncation */
  longlong count= args[1]->val_int();
  longlong byte_count;
  String *res= args[0]->val_str(str);
  String *rpad= args[2]->val_str(&rpad_str);

2703 2704 2705 2706
  if (!res || args[1]->null_value || !rpad || 
      ((count < 0) && !args[1]->unsigned_flag))
    goto err;
  null_value=0;
2707 2708
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Set here so that rest of code sees out-of-bound value as such. */
2709
  if ((ulonglong) count > INT_MAX32)
2710
    count= INT_MAX32;
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
  /*
    There is one exception not handled (intentionaly) by the character set
    aggregation code. If one string is strong side and is binary, and
    another one is weak side and is a multi-byte character string,
    then we need to operate on the second string in terms on bytes when
    calling ::numchars() and ::charpos(), rather than in terms of characters.
    Lets substitute its character set to binary.
  */
  if (collation.collation == &my_charset_bin)
  {
    res->set_charset(&my_charset_bin);
    rpad->set_charset(&my_charset_bin);
  }
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
#if MARIADB_VERSION_ID < 1000000
  /*
    Well-formedness is handled on a higher level in 10.0,
    no needs to check it here again.
  */
  else
  {
    // This will chop off any trailing illegal characters from rpad.
    String *well_formed_pad= args[2]->check_well_formed_result(rpad, false);
    if (!well_formed_pad)
      goto err;
  }
#endif
2737

2738
  if (count <= (res_char_length= res->numchars()))
2739
  {						// String to pad is big enough
2740
    res->length(res->charpos((int) count));	// Shorten result if longer
2741 2742
    return (res);
  }
2743
  pad_char_length= rpad->numchars();
2744 2745 2746

  byte_count= count * collation.collation->mbmaxlen;
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2747 2748 2749
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2750 2751
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
2752 2753
    goto err;
  }
unknown's avatar
unknown committed
2754
  if (args[2]->null_value || !pad_char_length)
unknown's avatar
unknown committed
2755
    goto err;
2756
  res_byte_length= res->length();	/* Must be done before alloc_buffer */
2757
  if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
unknown's avatar
unknown committed
2758 2759
    goto err;

2760
  to= (char*) res->ptr()+res_byte_length;
unknown's avatar
unknown committed
2761
  ptr_pad=rpad->ptr();
2762 2763 2764
  pad_byte_length= rpad->length();
  count-= res_char_length;
  for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
unknown's avatar
unknown committed
2765
  {
2766 2767
    memcpy(to,ptr_pad,pad_byte_length);
    to+= pad_byte_length;
unknown's avatar
unknown committed
2768
  }
2769 2770
  if (count)
  {
2771
    pad_byte_length= rpad->charpos((int) count);
2772 2773 2774
    memcpy(to,ptr_pad,(size_t) pad_byte_length);
    to+= pad_byte_length;
  }
2775
  res->length((uint) (to- (char*) res->ptr()));
unknown's avatar
unknown committed
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
  return (res);

 err:
  null_value=1;
  return 0;
}


void Item_func_lpad::fix_length_and_dec()
{
2786
  // Handle character set for args[0] and args[2].
2787
  if (agg_arg_charsets_for_string_result(collation, &args[0], 2, 2))
2788
    return;
2789
  
unknown's avatar
unknown committed
2790 2791
  if (args[1]->const_item())
  {
2792 2793 2794 2795
    ulonglong char_length= (ulonglong) args[1]->val_int();
    DBUG_ASSERT(collation.collation->mbmaxlen > 0);
    /* Assumes that the maximum length of a String is < INT_MAX32. */
    /* Set here so that rest of code sees out-of-bound value as such. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2796 2797 2798
    if (args[1]->null_value)
      char_length= 0;
    else if (char_length > INT_MAX32)
2799 2800
      char_length= INT_MAX32;
    fix_char_length_ulonglong(char_length);
unknown's avatar
unknown committed
2801 2802 2803
  }
  else
  {
2804
    max_length= MAX_BLOB_WIDTH;
2805
    maybe_null= 1;
unknown's avatar
unknown committed
2806 2807 2808 2809 2810 2811
  }
}


String *Item_func_lpad::val_str(String *str)
{
2812
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2813
  uint32 res_char_length,pad_char_length;
2814 2815 2816
  /* must be longlong to avoid truncation */
  longlong count= args[1]->val_int();
  longlong byte_count;
2817 2818
  String *res= args[0]->val_str(&tmp_value);
  String *pad= args[2]->val_str(&lpad_str);
unknown's avatar
unknown committed
2819

2820 2821 2822 2823
  if (!res || args[1]->null_value || !pad ||  
      ((count < 0) && !args[1]->unsigned_flag))
    goto err;  
  null_value=0;
2824 2825
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Set here so that rest of code sees out-of-bound value as such. */
2826
  if ((ulonglong) count > INT_MAX32)
2827
    count= INT_MAX32;
2828

2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
  /*
    There is one exception not handled (intentionaly) by the character set
    aggregation code. If one string is strong side and is binary, and
    another one is weak side and is a multi-byte character string,
    then we need to operate on the second string in terms on bytes when
    calling ::numchars() and ::charpos(), rather than in terms of characters.
    Lets substitute its character set to binary.
  */
  if (collation.collation == &my_charset_bin)
  {
    res->set_charset(&my_charset_bin);
    pad->set_charset(&my_charset_bin);
  }
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
#if MARIADB_VERSION_ID < 1000000
  /*
    Well-formedness is handled on a higher level in 10.0,
    no needs to check it here again.
  */  else
  {
    // This will chop off any trailing illegal characters from pad.
    String *well_formed_pad= args[2]->check_well_formed_result(pad, false);
    if (!well_formed_pad)
      goto err;
  }
#endif
2854

2855 2856 2857 2858
  res_char_length= res->numchars();

  if (count <= res_char_length)
  {
2859
    res->length(res->charpos((int) count));
2860
    return res;
2861
  }
2862 2863 2864 2865
  
  pad_char_length= pad->numchars();
  byte_count= count * collation.collation->mbmaxlen;
  
unknown's avatar
unknown committed
2866
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2867 2868 2869
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2870 2871
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
2872 2873 2874
    goto err;
  }

2875 2876
  if (args[2]->null_value || !pad_char_length ||
      str->alloc((uint32) byte_count))
unknown's avatar
unknown committed
2877
    goto err;
2878 2879 2880 2881 2882
  
  str->length(0);
  str->set_charset(collation.collation);
  count-= res_char_length;
  while (count >= pad_char_length)
unknown's avatar
unknown committed
2883
  {
2884 2885
    str->append(*pad);
    count-= pad_char_length;
unknown's avatar
unknown committed
2886
  }
2887
  if (count > 0)
2888
    str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
2889

2890 2891 2892
  str->append(*res);
  null_value= 0;
  return str;
unknown's avatar
unknown committed
2893

2894 2895
err:
  null_value= 1;
unknown's avatar
unknown committed
2896 2897 2898 2899 2900 2901
  return 0;
}


String *Item_func_conv::val_str(String *str)
{
2902
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2903 2904 2905 2906 2907
  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();
2908
  int err;
unknown's avatar
unknown committed
2909

2910
  // Note that abs(INT_MIN) is undefined.
unknown's avatar
unknown committed
2911
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
2912
      from_base == INT_MIN || to_base == INT_MIN ||
unknown's avatar
unknown committed
2913 2914 2915
      abs(to_base) > 36 || abs(to_base) < 2 ||
      abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
  {
2916 2917
    null_value= 1;
    return NULL;
unknown's avatar
unknown committed
2918
  }
2919
  null_value= 0;
unknown's avatar
unknown committed
2920
  unsigned_flag= !(from_base < 0);
2921 2922 2923 2924 2925 2926 2927 2928 2929 2930

  if (args[0]->field_type() == MYSQL_TYPE_BIT) 
  {
    /* 
     Special case: The string representation of BIT doesn't resemble the
     decimal representation, so we shouldn't change it to string and then to
     decimal. 
    */
    dec= args[0]->val_int();
  }
unknown's avatar
unknown committed
2931
  else
2932 2933 2934 2935 2936 2937 2938 2939 2940
  {
    if (from_base < 0)
      dec= my_strntoll(res->charset(), res->ptr(), res->length(),
                       -from_base, &endptr, &err);
    else
      dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
                                   from_base, &endptr, &err);
  }

2941 2942
  if (!(ptr= longlong2str(dec, ans, to_base)) ||
      str->copy(ans, (uint32) (ptr - ans), default_charset()))
2943 2944 2945 2946
  {
    null_value= 1;
    return NULL;
  }
unknown's avatar
unknown committed
2947 2948 2949
  return str;
}

unknown's avatar
unknown committed
2950

2951 2952
String *Item_func_conv_charset::val_str(String *str)
{
2953
  DBUG_ASSERT(fixed == 1);
2954
  if (use_cached_value)
2955
    return null_value ? 0 : &str_value;
2956
  String *arg= args[0]->val_str(str);
unknown's avatar
unknown committed
2957
  uint dummy_errors;
unknown's avatar
unknown committed
2958
  if (args[0]->null_value)
2959 2960 2961 2962
  {
    null_value=1;
    return 0;
  }
2963
  null_value= tmp_value.copy(arg->ptr(), arg->length(), arg->charset(),
unknown's avatar
unknown committed
2964
                             conv_charset, &dummy_errors);
2965
  return null_value ? 0 : check_well_formed_result(&tmp_value);
2966 2967 2968 2969
}

void Item_func_conv_charset::fix_length_and_dec()
{
2970
  collation.set(conv_charset, DERIVATION_IMPLICIT);
2971
  fix_char_length(args[0]->max_char_length());
2972 2973
}

2974
void Item_func_conv_charset::print(String *str, enum_query_type query_type)
2975
{
2976
  str->append(STRING_WITH_LEN("convert("));
2977
  args[0]->print(str, query_type);
2978
  str->append(STRING_WITH_LEN(" using "));
2979 2980 2981
  str->append(conv_charset->csname);
  str->append(')');
}
unknown's avatar
unknown committed
2982 2983 2984

String *Item_func_set_collation::val_str(String *str)
{
2985
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2986
  str=args[0]->val_str(str);
unknown's avatar
unknown committed
2987 2988
  if ((null_value=args[0]->null_value))
    return 0;
2989
  str->set_charset(collation.collation);
unknown's avatar
unknown committed
2990 2991 2992
  return str;
}

2993
void Item_func_set_collation::fix_length_and_dec()
unknown's avatar
unknown committed
2994
{
unknown's avatar
unknown committed
2995 2996
  CHARSET_INFO *set_collation;
  const char *colname;
2997
  String tmp, *str= args[1]->val_str(&tmp);
unknown's avatar
unknown committed
2998
  colname= str->c_ptr();
unknown's avatar
unknown committed
2999
  if (colname == binary_keyword)
3000
    set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
unknown's avatar
unknown committed
3001 3002
					 MY_CS_BINSORT,MYF(0));
  else
3003 3004 3005 3006 3007 3008 3009
  {
    if (!(set_collation= get_charset_by_name(colname,MYF(0))))
    {
      my_error(ER_UNKNOWN_COLLATION, MYF(0), colname);
      return;
    }
  }
unknown's avatar
unknown committed
3010

3011 3012
  if (!set_collation || 
      !my_charset_same(args[0]->collation.collation,set_collation))
3013
  {
3014 3015
    my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
             colname, args[0]->collation.collation->csname);
3016
    return;
3017
  }
3018 3019
  collation.set(set_collation, DERIVATION_EXPLICIT,
                args[0]->collation.repertoire);
3020
  max_length= args[0]->max_length;
unknown's avatar
unknown committed
3021 3022
}

3023

3024 3025 3026 3027 3028 3029 3030 3031 3032
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 ||
3033
      functype() != item_func->functype())
3034 3035
    return 0;
  Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
3036
  if (collation.collation != item_func_sc->collation.collation)
3037 3038 3039 3040 3041 3042 3043
    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;
}

3044

3045
void Item_func_set_collation::print(String *str, enum_query_type query_type)
3046 3047
{
  str->append('(');
3048
  args[0]->print(str, query_type);
3049
  str->append(STRING_WITH_LEN(" collate "));
3050 3051 3052 3053 3054 3055
  DBUG_ASSERT(args[1]->basic_const_item() &&
              args[1]->type() == Item::STRING_ITEM);
  args[1]->str_value.print(str);
  str->append(')');
}

3056 3057
String *Item_func_charset::val_str(String *str)
{
3058
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3059
  uint dummy_errors;
3060

3061
  CHARSET_INFO *cs= args[0]->charset_for_protocol(); 
3062
  null_value= 0;
3063
  str->copy(cs->csname, (uint) strlen(cs->csname),
unknown's avatar
unknown committed
3064
	    &my_charset_latin1, collation.collation, &dummy_errors);
unknown's avatar
unknown committed
3065 3066 3067 3068 3069
  return str;
}

String *Item_func_collation::val_str(String *str)
{
3070
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3071
  uint dummy_errors;
3072
  CHARSET_INFO *cs= args[0]->charset_for_protocol(); 
unknown's avatar
unknown committed
3073

3074
  null_value= 0;
3075
  str->copy(cs->name, (uint) strlen(cs->name),
unknown's avatar
unknown committed
3076
	    &my_charset_latin1, collation.collation, &dummy_errors);
3077 3078
  return str;
}
unknown's avatar
unknown committed
3079 3080


3081
String *Item_func_hex::val_str_ascii(String *str)
unknown's avatar
unknown committed
3082
{
unknown's avatar
unknown committed
3083
  String *res;
3084
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3085 3086
  if (args[0]->result_type() != STRING_RESULT)
  {
3087
    ulonglong dec;
unknown's avatar
unknown committed
3088
    char ans[65],*ptr;
3089
    /* Return hex of unsigned longlong value */
unknown's avatar
unknown committed
3090 3091
    if (args[0]->result_type() == REAL_RESULT ||
        args[0]->result_type() == DECIMAL_RESULT)
3092
    {
unknown's avatar
unknown committed
3093
      double val= args[0]->val_real();
3094 3095 3096 3097 3098 3099 3100 3101 3102
      if ((val <= (double) LONGLONG_MIN) || 
          (val >= (double) (ulonglong) ULONGLONG_MAX))
        dec=  ~(longlong) 0;
      else
        dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
    }
    else
      dec= (ulonglong) args[0]->val_int();

unknown's avatar
unknown committed
3103 3104
    if ((null_value= args[0]->null_value))
      return 0;
3105 3106 3107 3108
    
    if (!(ptr= longlong2str(dec, ans, 16)) ||
        str->copy(ans,(uint32) (ptr - ans),
        &my_charset_numeric))
Martin Hansson's avatar
Martin Hansson committed
3109
      return make_empty_result();		// End of memory
unknown's avatar
unknown committed
3110 3111 3112 3113
    return str;
  }

  /* Convert given string to a hex string, character by character */
unknown's avatar
unknown committed
3114 3115
  res= args[0]->val_str(str);
  if (!res || tmp_value.alloc(res->length()*2+1))
unknown's avatar
unknown committed
3116 3117 3118 3119 3120 3121
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  tmp_value.length(res->length()*2);
3122
  tmp_value.set_charset(&my_charset_latin1);
unknown's avatar
unknown committed
3123 3124

  octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
unknown's avatar
unknown committed
3125 3126 3127
  return &tmp_value;
}

unknown's avatar
unknown committed
3128
  /** Convert given hex string to a binary string. */
unknown's avatar
unknown committed
3129

unknown's avatar
unknown committed
3130 3131
String *Item_func_unhex::val_str(String *str)
{
unknown's avatar
unknown committed
3132 3133 3134 3135
  const char *from, *end;
  char *to;
  String *res;
  uint length;
3136
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3137

unknown's avatar
unknown committed
3138 3139
  res= args[0]->val_str(str);
  if (!res || tmp_value.alloc(length= (1+res->length())/2))
unknown's avatar
unknown committed
3140 3141 3142 3143
  {
    null_value=1;
    return 0;
  }
unknown's avatar
unknown committed
3144

unknown's avatar
unknown committed
3145 3146 3147
  from= res->ptr();
  null_value= 0;
  tmp_value.length(length);
unknown's avatar
unknown committed
3148 3149 3150
  to= (char*) tmp_value.ptr();
  if (res->length() % 2)
  {
unknown's avatar
unknown committed
3151 3152 3153
    int hex_char;
    *to++= hex_char= hexchar_to_int(*from++);
    if ((null_value= (hex_char == -1)))
unknown's avatar
unknown committed
3154 3155 3156 3157
      return 0;
  }
  for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
  {
unknown's avatar
unknown committed
3158 3159 3160
    int hex_char;
    *to= (hex_char= hexchar_to_int(from[0])) << 4;
    if ((null_value= (hex_char == -1)))
unknown's avatar
unknown committed
3161
      return 0;
unknown's avatar
unknown committed
3162 3163
    *to|= hex_char= hexchar_to_int(from[1]);
    if ((null_value= (hex_char == -1)))
unknown's avatar
unknown committed
3164 3165 3166 3167
      return 0;
  }
  return &tmp_value;
}
unknown's avatar
unknown committed
3168

unknown's avatar
unknown committed
3169

3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
#ifndef DBUG_OFF
String *Item_func_like_range::val_str(String *str)
{
  DBUG_ASSERT(fixed == 1);
  longlong nbytes= args[1]->val_int();
  String *res= args[0]->val_str(str);
  size_t min_len, max_len;
  CHARSET_INFO *cs= collation.collation;

  if (!res || args[0]->null_value || args[1]->null_value ||
      nbytes < 0 || nbytes > MAX_BLOB_WIDTH ||
      min_str.alloc(nbytes) || max_str.alloc(nbytes))
    goto err;
  null_value=0;

  if (cs->coll->like_range(cs, res->ptr(), res->length(),
                           '\\', '_', '%', nbytes,
                           (char*) min_str.ptr(), (char*) max_str.ptr(),
                           &min_len, &max_len))
    goto err;

  min_str.set_charset(collation.collation);
  max_str.set_charset(collation.collation);
  min_str.length(min_len);
  max_str.length(max_len);

  return is_min ? &min_str : &max_str;

err:
  null_value= 1;
  return 0;
}
#endif


3205
void Item_func_binary::print(String *str, enum_query_type query_type)
3206
{
3207
  str->append(STRING_WITH_LEN("cast("));
3208
  args[0]->print(str, query_type);
3209
  str->append(STRING_WITH_LEN(" as binary)"));
3210 3211 3212
}


unknown's avatar
unknown committed
3213 3214 3215 3216
#include <my_dir.h>				// For my_stat

String *Item_load_file::val_str(String *str)
{
3217
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3218 3219 3220
  String *file_name;
  File file;
  MY_STAT stat_info;
3221
  char path[FN_REFLEN];
unknown's avatar
unknown committed
3222 3223
  DBUG_ENTER("load_file");

3224
  if (!(file_name= args[0]->val_str(str))
unknown's avatar
SCRUM:  
unknown committed
3225
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3226
      || !(current_thd->security_ctx->master_access & FILE_ACL)
unknown's avatar
SCRUM:  
unknown committed
3227
#endif
3228
      )
unknown's avatar
unknown committed
3229
    goto err;
3230

3231
  (void) fn_format(path, file_name->c_ptr_safe(), mysql_real_data_home, "",
unknown's avatar
unknown committed
3232
		   MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
3233

3234
  /* Read only allowed from within dir specified by secure_file_priv */
3235
  if (!is_secure_file_path(path))
3236 3237
    goto err;

Marc Alff's avatar
Marc Alff committed
3238
  if (!mysql_file_stat(key_file_loadfile, path, &stat_info, MYF(0)))
3239 3240
    goto err;

unknown's avatar
unknown committed
3241 3242 3243 3244 3245
  if (!(stat_info.st_mode & S_IROTH))
  {
    /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
    goto err;
  }
unknown's avatar
unknown committed
3246
  if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
unknown's avatar
unknown committed
3247
  {
3248 3249
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3250 3251
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
unknown's avatar
unknown committed
3252 3253
    goto err;
  }
3254
  if (tmp_value.alloc((size_t)stat_info.st_size))
unknown's avatar
unknown committed
3255
    goto err;
Marc Alff's avatar
Marc Alff committed
3256 3257
  if ((file= mysql_file_open(key_file_loadfile,
                             file_name->ptr(), O_RDONLY, MYF(0))) < 0)
unknown's avatar
unknown committed
3258
    goto err;
Marc Alff's avatar
Marc Alff committed
3259 3260
  if (mysql_file_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size,
                      MYF(MY_NABP)))
unknown's avatar
unknown committed
3261
  {
Marc Alff's avatar
Marc Alff committed
3262
    mysql_file_close(file, MYF(0));
unknown's avatar
unknown committed
3263 3264
    goto err;
  }
3265
  tmp_value.length((uint32)stat_info.st_size);
Marc Alff's avatar
Marc Alff committed
3266
  mysql_file_close(file, MYF(0));
unknown's avatar
unknown committed
3267
  null_value = 0;
unknown's avatar
unknown committed
3268
  DBUG_RETURN(&tmp_value);
unknown's avatar
unknown committed
3269 3270 3271 3272 3273 3274 3275 3276 3277

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


String* Item_func_export_set::val_str(String* str)
{
3278
  DBUG_ASSERT(fixed == 1);
3279 3280 3281 3282 3283
  String yes_buf, no_buf, sep_buf;
  const ulonglong the_set = (ulonglong) args[0]->val_int();
  const String *yes= args[1]->val_str(&yes_buf);
  const String *no= args[2]->val_str(&no_buf);
  const String *sep= NULL;
unknown's avatar
unknown committed
3284 3285 3286

  uint num_set_values = 64;
  str->length(0);
3287
  str->set_charset(collation.collation);
unknown's avatar
unknown committed
3288 3289 3290 3291

  /* Check if some argument is a NULL value */
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
  {
3292 3293
    null_value= true;
    return NULL;
unknown's avatar
unknown committed
3294
  }
3295 3296 3297 3298
  /*
    Arg count can only be 3, 4 or 5 here. This is guaranteed from the
    grammar for EXPORT_SET()
  */
unknown's avatar
unknown committed
3299 3300 3301 3302 3303 3304 3305
  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)
    {
3306 3307
      null_value= true;
      return NULL;
unknown's avatar
unknown committed
3308 3309 3310 3311 3312
    }
    /* Fall through */
  case 4:
    if (!(sep = args[3]->val_str(&sep_buf)))	// Only true if NULL
    {
3313 3314
      null_value= true;
      return NULL;
unknown's avatar
unknown committed
3315 3316 3317
    }
    break;
  case 3:
3318 3319 3320
    {
      /* errors is not checked - assume "," can always be converted */
      uint errors;
3321 3322
      sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin,
                   collation.collation, &errors);
3323 3324
      sep = &sep_buf;
    }
3325 3326 3327
    break;
  default:
    DBUG_ASSERT(0); // cannot happen
unknown's avatar
unknown committed
3328
  }
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345
  null_value= false;

  const ulong max_allowed_packet= current_thd->variables.max_allowed_packet;
  const uint num_separators= num_set_values > 0 ? num_set_values - 1 : 0;
  const ulonglong max_total_length=
    num_set_values * max(yes->length(), no->length()) +
    num_separators * sep->length();

  if (unlikely(max_total_length > max_allowed_packet))
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_WARN_ALLOWED_PACKET_OVERFLOWED,
                        ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
                        func_name(), max_allowed_packet);
    null_value= true;
    return NULL;
  }
unknown's avatar
unknown committed
3346

3347 3348 3349
  uint ix;
  ulonglong mask;
  for (ix= 0, mask=0x1; ix < num_set_values; ++ix, mask = (mask << 1))
unknown's avatar
unknown committed
3350 3351 3352 3353 3354
  {
    if (the_set & mask)
      str->append(*yes);
    else
      str->append(*no);
3355
    if (ix != num_separators)
unknown's avatar
unknown committed
3356 3357 3358 3359 3360 3361 3362
      str->append(*sep);
  }
  return str;
}

void Item_func_export_set::fix_length_and_dec()
{
3363 3364
  uint32 length= max(args[1]->max_char_length(), args[2]->max_char_length());
  uint32 sep_length= (arg_count > 3 ? args[3]->max_char_length() : 1);
3365

3366 3367
  if (agg_arg_charsets_for_string_result(collation,
                                         args + 1, min(4, arg_count) - 1))
unknown's avatar
unknown committed
3368
    return;
3369
  fix_char_length(length * 64 + sep_length * 63);
unknown's avatar
unknown committed
3370 3371 3372 3373
}

String* Item_func_inet_ntoa::val_str(String* str)
{
3374
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3375 3376 3377
  uchar buf[8], *p;
  ulonglong n = (ulonglong) args[0]->val_int();
  char num[4];
unknown's avatar
unknown committed
3378

unknown's avatar
unknown committed
3379
  /*
unknown's avatar
unknown committed
3380
    We do not know if args[0] is NULL until we have called
unknown's avatar
unknown committed
3381
    some val function on it if args[0] is not a constant!
unknown's avatar
unknown committed
3382 3383

    Also return null if n > 255.255.255.255
unknown's avatar
unknown committed
3384
  */
unknown's avatar
unknown committed
3385
  if ((null_value= (args[0]->null_value || n > (ulonglong) LL(4294967295))))
unknown's avatar
unknown committed
3386
    return 0;					// Null value
unknown's avatar
unknown committed
3387

3388
  str->set_charset(collation.collation);
unknown's avatar
unknown committed
3389
  str->length(0);
unknown's avatar
unknown committed
3390
  int4store(buf,n);
unknown's avatar
unknown committed
3391

unknown's avatar
unknown committed
3392
  /* Now we can assume little endian. */
3393

unknown's avatar
unknown committed
3394
  num[3]='.';
unknown's avatar
unknown committed
3395
  for (p=buf+4 ; p-- > buf ; )
unknown's avatar
unknown committed
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
  {
    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';
3406 3407 3408 3409
    uint length= (n1 ? 4 : n2 ? 3 : 2);         // Remove pre-zero
    uint dot_length= (p <= buf) ? 1 : 0;
    (void) str->append(num + 4 - length, length - dot_length,
                       &my_charset_latin1);
unknown's avatar
unknown committed
3410 3411 3412
  }
  return str;
}
unknown's avatar
unknown committed
3413

unknown's avatar
unknown committed
3414

unknown's avatar
unknown committed
3415 3416 3417
#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))

/**
3418 3419 3420
  QUOTE() function returns argument string in single quotes suitable for
  using in a SQL statement.

unknown's avatar
unknown committed
3421 3422 3423
  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
  running commands from a file in windows.
3424

unknown's avatar
unknown committed
3425
  This function is very useful when you want to generate SQL statements.
3426

unknown's avatar
unknown committed
3427
  @note
3428 3429
    QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).

unknown's avatar
unknown committed
3430 3431 3432 3433
  @retval
    str	   Quoted string
  @retval
    NULL	   Out of memory.
3434
*/
3435

unknown's avatar
unknown committed
3436 3437
String *Item_func_quote::val_str(String *str)
{
3438
  DBUG_ASSERT(fixed == 1);
3439 3440 3441
  /*
    Bit mask that has 1 for set for the position of the following characters:
    0, \, ' and ^Z
3442
  */
3443

3444
  static uchar escmask[32]=
3445 3446 3447 3448 3449 3450
  {
    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
  };
unknown's avatar
unknown committed
3451

3452
  ulong max_allowed_packet= current_thd->variables.max_allowed_packet;
3453 3454 3455 3456
  char *from, *to, *end, *start;
  String *arg= args[0]->val_str(str);
  uint arg_length, new_length;
  if (!arg)					// Null argument
3457
  {
3458 3459
    /* Return the string 'NULL' */
    str->copy(STRING_WITH_LEN("NULL"), collation.collation);
3460 3461 3462 3463
    null_value= 0;
    return str;
  }

3464
  arg_length= arg->length();
3465

3466 3467 3468 3469 3470
  if (collation.collation->mbmaxlen == 1)
  {
    new_length= arg_length + 2; /* for beginning and ending ' signs */
    for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
      new_length+= get_esc_bit(escmask, (uchar) *from);
3471 3472
    if (new_length > max_allowed_packet)
      goto toolong;
3473 3474 3475 3476 3477
  }
  else
  {
    new_length= (arg_length * 2) +  /* For string characters */
                (2 * collation.collation->mbmaxlen); /* For quotes */
3478
    set_if_smaller(new_length, max_allowed_packet);
3479
  }
unknown's avatar
unknown committed
3480

3481
  if (tmp_value.alloc(new_length))
3482
    goto null;
3483

3484 3485 3486 3487 3488 3489 3490 3491 3492 3493
  if (collation.collation->mbmaxlen > 1)
  {
    CHARSET_INFO *cs= collation.collation;
    int mblen;
    uchar *to_end;
    to= (char*) tmp_value.ptr();
    to_end= (uchar*) to + new_length;

    /* Put leading quote */
    if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
3494
      goto toolong;
3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513
    to+= mblen;

    for (start= (char*) arg->ptr(), end= start + arg_length; start < end; )
    {
      my_wc_t wc;
      bool escape;
      if ((mblen= cs->cset->mb_wc(cs, &wc, (uchar*) start, (uchar*) end)) <= 0)
        goto null;
      start+= mblen;
      switch (wc) {
        case 0:      escape= 1; wc= '0'; break;
        case '\032': escape= 1; wc= 'Z'; break;
        case '\'':   escape= 1; break;
        case '\\':   escape= 1; break;
        default:     escape= 0; break;
      }
      if (escape)
      {
        if ((mblen= cs->cset->wc_mb(cs, '\\', (uchar*) to, to_end)) <= 0)
3514
          goto toolong;
3515 3516 3517
        to+= mblen;
      }
      if ((mblen= cs->cset->wc_mb(cs, wc, (uchar*) to, to_end)) <= 0)
3518
        goto toolong;
3519 3520 3521 3522 3523
      to+= mblen;
    }

    /* Put trailing quote */
    if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
3524
      goto toolong;
3525 3526 3527 3528 3529
    to+= mblen;
    new_length= to - tmp_value.ptr();
    goto ret;
  }

3530
  /*
3531
    We replace characters from the end to the beginning
3532
  */
3533
  to= (char*) tmp_value.ptr() + new_length - 1;
3534
  *to--= '\'';
unknown's avatar
unknown committed
3535
  for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
unknown's avatar
unknown committed
3536
  {
3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
    /*
      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;
    }
unknown's avatar
unknown committed
3559
  }
3560
  *to= '\'';
3561 3562

ret:
3563
  tmp_value.length(new_length);
unknown's avatar
unknown committed
3564
  tmp_value.set_charset(collation.collation);
3565
  null_value= 0;
3566
  return &tmp_value;
3567

3568 3569 3570 3571 3572
toolong:
  push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                      ER_WARN_ALLOWED_PACKET_OVERFLOWED,
                      ER_THD(current_thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
                      func_name(), max_allowed_packet);
3573 3574 3575
null:
  null_value= 1;
  return 0;
unknown's avatar
unknown committed
3576
}
unknown's avatar
unknown committed
3577

3578 3579
longlong Item_func_uncompressed_length::val_int()
{
3580
  DBUG_ASSERT(fixed == 1);
3581 3582 3583 3584 3585 3586 3587 3588
  String *res= args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  if (res->is_empty()) return 0;
unknown's avatar
fixed:  
unknown committed
3589 3590

  /*
3591 3592 3593 3594 3595
    If length is <= 4 bytes, data is corrupt. This is the best we can do
    to detect garbage input without decompressing it.
  */
  if (res->length() <= 4)
  {
Marc Alff's avatar
Marc Alff committed
3596
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
3597 3598 3599 3600 3601 3602 3603 3604 3605
                        ER_ZLIB_Z_DATA_ERROR,
                        ER(ER_ZLIB_Z_DATA_ERROR));
    null_value= 1;
    return 0;
  }

 /*
    res->ptr() using is safe because we have tested that string is at least
    5 bytes long.
unknown's avatar
fixed:  
unknown committed
3606 3607 3608 3609 3610 3611
    res->c_ptr() is not used because:
      - we do not need \0 terminated string to get first 4 bytes
      - c_ptr() tests simbol after string end (uninitialiozed memory) which
        confuse valgrind
  */
  return uint4korr(res->ptr()) & 0x3FFFFFFF;
3612 3613 3614 3615
}

longlong Item_func_crc32::val_int()
{
3616
  DBUG_ASSERT(fixed == 1);
3617 3618 3619 3620 3621 3622 3623
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
3624
  return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
3625 3626
}

unknown's avatar
unknown committed
3627
#ifdef HAVE_COMPRESS
3628
#include "zlib.h"
unknown's avatar
unknown committed
3629 3630 3631

String *Item_func_compress::val_str(String *str)
{
unknown's avatar
unknown committed
3632
  int err= Z_OK, code;
3633
  size_t new_size;
unknown's avatar
unknown committed
3634 3635 3636
  String *res;
  Byte *body;
  char *tmp, *last_char;
3637
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3638 3639

  if (!(res= args[0]->val_str(str)))
3640 3641 3642 3643
  {
    null_value= 1;
    return 0;
  }
3644
  null_value= 0;
3645 3646
  if (res->is_empty()) return res;

unknown's avatar
unknown committed
3647
  /*
unknown's avatar
unknown committed
3648
    Citation from zlib.h (comment for compress function):
unknown's avatar
unknown committed
3649 3650

    Compresses the source buffer into the destination buffer.  sourceLen is
unknown's avatar
unknown committed
3651 3652 3653 3654
    the byte length of the source buffer. Upon entry, destLen is the total
    size of the destination buffer, which must be at least 0.1% larger than
    sourceLen plus 12 bytes.
    We assume here that the buffer can't grow more than .25 %.
unknown's avatar
unknown committed
3655
  */
unknown's avatar
unknown committed
3656
  new_size= res->length() + res->length() / 5 + 12;
unknown's avatar
unknown committed
3657

unknown's avatar
unknown committed
3658 3659
  // Check new_size overflow: new_size <= res->length()
  if (((uint32) (new_size+5) <= res->length()) || 
3660 3661 3662 3663 3664
      buffer.realloc((uint32) new_size + 4 + 1))
  {
    null_value= 1;
    return 0;
  }
unknown's avatar
fixed:  
unknown committed
3665

unknown's avatar
unknown committed
3666
  body= ((Byte*)buffer.ptr()) + 4;
3667

unknown's avatar
fixed:  
unknown committed
3668
  // As far as we have checked res->is_empty() we can use ptr()
3669 3670
  if ((err= my_compress_buffer(body, &new_size, (const uchar *)res->ptr(),
                               res->length())) != Z_OK)
unknown's avatar
unknown committed
3671 3672
  {
    code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
Marc Alff's avatar
Marc Alff committed
3673
    push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,code,ER(code));
unknown's avatar
unknown committed
3674 3675 3676
    null_value= 1;
    return 0;
  }
3677

unknown's avatar
unknown committed
3678
  tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
3679
  int4store(tmp, res->length() & 0x3FFFFFFF);
3680

unknown's avatar
unknown committed
3681 3682
  /* This is to ensure that things works for CHAR fields, which trim ' ': */
  last_char= ((char*)body)+new_size-1;
unknown's avatar
unknown committed
3683 3684 3685 3686 3687
  if (*last_char == ' ')
  {
    *++last_char= '.';
    new_size++;
  }
3688

3689
  buffer.length((uint32)new_size + 4);
unknown's avatar
unknown committed
3690 3691 3692
  return &buffer;
}

3693

unknown's avatar
unknown committed
3694 3695
String *Item_func_uncompress::val_str(String *str)
{
3696
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3697
  String *res= args[0]->val_str(str);
3698 3699
  ulong new_size;
  int err;
unknown's avatar
unknown committed
3700
  uint code;
3701

3702 3703
  if (!res)
    goto err;
3704
  null_value= 0;
3705 3706 3707
  if (res->is_empty())
    return res;

3708 3709 3710
  /* If length is less than 4 bytes, data is corrupt */
  if (res->length() <= 4)
  {
Marc Alff's avatar
Marc Alff committed
3711
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,
3712 3713 3714 3715 3716 3717
			ER_ZLIB_Z_DATA_ERROR,
			ER(ER_ZLIB_Z_DATA_ERROR));
    goto err;
  }

  /* Size of uncompressed data is stored as first 4 bytes of field */
3718
  new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
3719
  if (new_size > current_thd->variables.max_allowed_packet)
unknown's avatar
unknown committed
3720
  {
Marc Alff's avatar
Marc Alff committed
3721
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,
unknown's avatar
unknown committed
3722
			ER_TOO_BIG_FOR_UNCOMPRESS,
3723
			ER(ER_TOO_BIG_FOR_UNCOMPRESS),
3724 3725
                        static_cast<int>(current_thd->variables.
                                         max_allowed_packet));
3726
    goto err;
unknown's avatar
unknown committed
3727
  }
3728 3729
  if (buffer.realloc((uint32)new_size))
    goto err;
3730

3731
  if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
3732
		       ((const Bytef*)res->ptr())+4,res->length()-4)) == Z_OK)
unknown's avatar
unknown committed
3733
  {
3734
    buffer.length((uint32) new_size);
unknown's avatar
unknown committed
3735 3736
    return &buffer;
  }
3737

3738 3739
  code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
	 ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
Marc Alff's avatar
Marc Alff committed
3740
  push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,code,ER(code));
3741 3742

err:
unknown's avatar
unknown committed
3743 3744 3745 3746
  null_value= 1;
  return 0;
}
#endif
unknown's avatar
unknown committed
3747 3748 3749 3750


String *Item_func_uuid::val_str(String *str)
{
3751
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3752
  uchar guid[MY_UUID_SIZE];
3753

unknown's avatar
unknown committed
3754 3755
  str->realloc(MY_UUID_STRING_LENGTH+1);
  str->length(MY_UUID_STRING_LENGTH);
unknown's avatar
unknown committed
3756
  str->set_charset(system_charset_info);
unknown's avatar
unknown committed
3757 3758 3759
  my_uuid(guid);
  my_uuid2str(guid, (char *)str->ptr());

unknown's avatar
unknown committed
3760 3761
  return str;
}
3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779


Item_func_dyncol_create::Item_func_dyncol_create(List<Item> &args,
                                                 DYNCALL_CREATE_DEF *dfs)
  : Item_str_func(args), defs(dfs), vals(0), nums(0)
{
  DBUG_ASSERT((args.elements & 0x1) == 0); // even number of arguments
}


bool Item_func_dyncol_create::fix_fields(THD *thd, Item **ref)
{
  bool res= Item_func::fix_fields(thd, ref); // no need Item_str_func here
  vals= (DYNAMIC_COLUMN_VALUE *) alloc_root(thd->mem_root,
                                            sizeof(DYNAMIC_COLUMN_VALUE) *
                                            (arg_count / 2));
  nums= (uint *) alloc_root(thd->mem_root,
                            sizeof(uint) * (arg_count / 2));
Michael Widenius's avatar
Michael Widenius committed
3780
  status_var_increment(thd->status_var.feature_dynamic_columns);
3781 3782 3783 3784 3785 3786
  return res || vals == 0 || nums == 0;
}


void Item_func_dyncol_create::fix_length_and_dec()
{
3787
  maybe_null= TRUE;
3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822
  collation.set(&my_charset_bin);
  decimals= 0;
}

void Item_func_dyncol_create::prepare_arguments()
{
  char buff[STRING_BUFFER_USUAL_SIZE];
  String *res, tmp(buff, sizeof(buff), &my_charset_bin);
  uint column_count= (arg_count / 2);
  uint i;
  my_decimal dtmp, *dres;

  /* get values */
  for (i= 0; i < column_count; i++)
  {
    uint valpos= i * 2 + 1;
    DYNAMIC_COLUMN_TYPE type= defs[i].type;
    if (type == DYN_COL_NULL) // auto detect
    {
      /*
        We don't have a default here to ensure we get a warning if
        one adds a new not handled MYSQL_TYPE_...
      */
      switch (args[valpos]->field_type()) {
      case MYSQL_TYPE_DECIMAL:
      case MYSQL_TYPE_NEWDECIMAL:
        type= DYN_COL_DECIMAL;
        break;
      case MYSQL_TYPE_TINY:
      case MYSQL_TYPE_SHORT:
      case MYSQL_TYPE_LONG:
      case MYSQL_TYPE_LONGLONG:
      case MYSQL_TYPE_INT24:
      case MYSQL_TYPE_YEAR:
      case MYSQL_TYPE_BIT:
3823
        type= args[valpos]->unsigned_flag ? DYN_COL_UINT : DYN_COL_INT;
3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863
        break;
      case MYSQL_TYPE_FLOAT:
      case MYSQL_TYPE_DOUBLE:
        type= DYN_COL_DOUBLE;
        break;
      case MYSQL_TYPE_NULL:
        type= DYN_COL_NULL;
        break;
      case MYSQL_TYPE_TIMESTAMP:
      case MYSQL_TYPE_DATETIME:
        type= DYN_COL_DATETIME;
	break;
      case MYSQL_TYPE_DATE:
      case MYSQL_TYPE_NEWDATE:
        type= DYN_COL_DATE;
        break;
      case MYSQL_TYPE_TIME:
        type= DYN_COL_TIME;
        break;
      case MYSQL_TYPE_VARCHAR:
      case MYSQL_TYPE_ENUM:
      case MYSQL_TYPE_SET:
      case MYSQL_TYPE_TINY_BLOB:
      case MYSQL_TYPE_MEDIUM_BLOB:
      case MYSQL_TYPE_LONG_BLOB:
      case MYSQL_TYPE_BLOB:
      case MYSQL_TYPE_VAR_STRING:
      case MYSQL_TYPE_STRING:
      case MYSQL_TYPE_GEOMETRY:
        type= DYN_COL_STRING;
        break;
      }
    }
    nums[i]= (uint) args[i * 2]->val_int();
    vals[i].type= type;
    switch (type) {
    case DYN_COL_NULL:
      DBUG_ASSERT(args[valpos]->field_type() == MYSQL_TYPE_NULL);
      break;
    case DYN_COL_INT:
3864
      vals[i].x.long_value= args[valpos]->val_int();
3865 3866
      break;
    case DYN_COL_UINT:
3867
      vals[i].x.ulong_value= args[valpos]->val_int();
3868 3869
      break;
    case DYN_COL_DOUBLE:
3870
      vals[i].x.double_value= args[valpos]->val_real();
3871 3872 3873 3874
      break;
    case DYN_COL_STRING:
      res= args[valpos]->val_str(&tmp);
      if (res &&
3875
          (vals[i].x.string.value.str= my_strndup(res->ptr(), res->length(),
3876 3877
                                                MYF(MY_WME))))
      {
3878 3879
	vals[i].x.string.value.length= res->length();
	vals[i].x.string.charset= res->charset();
3880 3881 3882 3883
      }
      else
      {
        args[valpos]->null_value= 1;            // In case of out of memory
3884 3885
        vals[i].x.string.value.str= NULL;
        vals[i].x.string.value.length= 0;         // just to be safe
3886 3887 3888 3889 3890 3891
      }
      break;
    case DYN_COL_DECIMAL:
      if ((dres= args[valpos]->val_decimal(&dtmp)))
      {
	dynamic_column_prepare_decimal(&vals[i]);
3892 3893 3894 3895 3896 3897
        DBUG_ASSERT(vals[i].x.decimal.value.len == dres->len);
        vals[i].x.decimal.value.intg= dres->intg;
        vals[i].x.decimal.value.frac= dres->frac;
        vals[i].x.decimal.value.sign= dres->sign();
        memcpy(vals[i].x.decimal.buffer, dres->buf,
               sizeof(vals[i].x.decimal.buffer));
3898 3899 3900 3901 3902 3903 3904 3905
      }
      else
      {
	dynamic_column_prepare_decimal(&vals[i]); // just to be safe
        DBUG_ASSERT(args[valpos]->null_value);
      }
      break;
    case DYN_COL_DATETIME:
3906
      args[valpos]->get_date(&vals[i].x.time_value, 0);
3907 3908
      break;
    case DYN_COL_DATE:
3909
      args[valpos]->get_date(&vals[i].x.time_value, 0);
3910 3911
      break;
    case DYN_COL_TIME:
3912
      args[valpos]->get_time(&vals[i].x.time_value);
3913 3914 3915 3916 3917 3918 3919 3920
      break;
    default:
      DBUG_ASSERT(0);
      vals[i].type= DYN_COL_NULL;
    }
    if (vals[i].type != DYN_COL_NULL && args[valpos]->null_value)
    {
      if (vals[i].type == DYN_COL_STRING)
Sergei Golubchik's avatar
Sergei Golubchik committed
3921
        my_free(vals[i].x.string.value.str);
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
      vals[i].type= DYN_COL_NULL;
    }
  }
}

void Item_func_dyncol_create::cleanup_arguments()
{
  uint column_count= (arg_count / 2);
  uint i;

  for (i= 0; i < column_count; i++)
  {
    if (vals[i].type == DYN_COL_STRING)
Sergei Golubchik's avatar
Sergei Golubchik committed
3935
      my_free(vals[i].x.string.value.str);
3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964
  }
}

String *Item_func_dyncol_create::val_str(String *str)
{
  DYNAMIC_COLUMN col;
  String *res;
  uint column_count= (arg_count / 2);
  enum enum_dyncol_func_result rc;
  DBUG_ASSERT((arg_count & 0x1) == 0); // even number of arguments

  prepare_arguments();

  if ((rc= dynamic_column_create_many(&col, column_count, nums, vals)))
  {
    dynamic_column_error_message(rc);
    dynamic_column_column_free(&col);
    res= NULL;
    null_value= TRUE;
  }
  else
  {
    /* Move result from DYNAMIC_COLUMN to str_value */
    char *ptr;
    size_t length, alloc_length;
    dynamic_column_reassociate(&col, &ptr, &length, &alloc_length);
    str_value.reassociate(ptr, (uint32) length, (uint32) alloc_length,
                          &my_charset_bin);
    res= &str_value;
3965
    null_value= FALSE;
3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068
  }

  /* cleanup */
  cleanup_arguments();

  return res;
}

void Item_func_dyncol_create::print_arguments(String *str,
                                              enum_query_type query_type)
{
  uint i;
  uint column_count= (arg_count / 2);
  for (i= 0; i < column_count; i++)
  {
    args[i*2]->print(str, query_type);
    str->append(',');
    args[i*2 + 1]->print(str, query_type);
    switch (defs[i].type) {
    case DYN_COL_NULL: // automatic type => write nothing
      break;
    case DYN_COL_INT:
      str->append(STRING_WITH_LEN(" AS int"));
      break;
    case DYN_COL_UINT:
      str->append(STRING_WITH_LEN(" AS unsigned int"));
      break;
    case DYN_COL_DOUBLE:
      str->append(STRING_WITH_LEN(" AS double"));
      break;
    case DYN_COL_STRING:
      str->append(STRING_WITH_LEN(" AS char"));
      if (defs[i].cs)
      {
        str->append(STRING_WITH_LEN(" charset "));
        str->append(defs[i].cs->csname);
        str->append(' ');
      }
      break;
    case DYN_COL_DECIMAL:
      str->append(STRING_WITH_LEN(" AS decimal"));
      break;
    case DYN_COL_DATETIME:
      str->append(STRING_WITH_LEN(" AS datetime"));
      break;
    case DYN_COL_DATE:
      str->append(STRING_WITH_LEN(" AS date"));
      break;
    case DYN_COL_TIME:
      str->append(STRING_WITH_LEN(" AS time"));
      break;
    }
    if (i < column_count - 1)
      str->append(',');
  }
}


void Item_func_dyncol_create::print(String *str,
                                    enum_query_type query_type)
{
  DBUG_ASSERT((arg_count & 0x1) == 0); // even number of arguments
  str->append(STRING_WITH_LEN("column_create("));
  print_arguments(str, query_type);
  str->append(')');
}


String *Item_func_dyncol_add::val_str(String *str)
{
  DYNAMIC_COLUMN col;
  String *res;
  uint column_count=  (arg_count / 2);
  enum enum_dyncol_func_result rc;
  DBUG_ASSERT((arg_count & 0x1) == 1); // odd number of arguments

  /* We store the packed data last */
  res= args[arg_count - 1]->val_str(str);
  if (args[arg_count - 1]->null_value)
    goto null;
  init_dynamic_string(&col, NULL, res->length() + STRING_BUFFER_USUAL_SIZE,
                      STRING_BUFFER_USUAL_SIZE);

  col.length= res->length();
  memcpy(col.str, res->ptr(), col.length);

  prepare_arguments();

  if ((rc= dynamic_column_update_many(&col, column_count, nums, vals)))
  {
    dynamic_column_error_message(rc);
    dynamic_column_column_free(&col);
    cleanup_arguments();
    goto null;
  }

  {
    /* Move result from DYNAMIC_COLUMN to str */
    char *ptr;
    size_t length, alloc_length;
    dynamic_column_reassociate(&col, &ptr, &length, &alloc_length);
    str->reassociate(ptr, (uint32) length, (uint32) alloc_length,
                     &my_charset_bin);
4069
    null_value= FALSE;
4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
  }

  /* cleanup */
  dynamic_column_column_free(&col);
  cleanup_arguments();

  return str;

null:
  null_value= TRUE;
  return NULL;
}


void Item_func_dyncol_add::print(String *str,
                                 enum_query_type query_type)
{
  DBUG_ASSERT((arg_count & 0x1) == 1); // odd number of arguments
  str->append(STRING_WITH_LEN("column_create("));
  args[arg_count - 1]->print(str, query_type);
  str->append(',');
  print_arguments(str, query_type);
  str->append(')');
}

4095 4096 4097 4098 4099 4100 4101 4102

/**
  Get value for a column stored in a dynamic column

  @notes
  This function ensures that null_value is set correctly
*/

4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151
bool Item_dyncol_get::get_dyn_value(DYNAMIC_COLUMN_VALUE *val, String *tmp)
{
  DYNAMIC_COLUMN dyn_str;
  String *res;
  longlong num;
  enum enum_dyncol_func_result rc;

  num= args[1]->val_int();
  if (args[1]->null_value || num < 0 || num > INT_MAX)
  {
    null_value= 1;
    return 1;
  }

  res= args[0]->val_str(tmp);
  if (args[0]->null_value)
  {
    null_value= 1;
    return 1;
  }

  dyn_str.str=   (char*) res->ptr();
  dyn_str.length= res->length();
  if ((rc= dynamic_column_get(&dyn_str, (uint) num, val)))
  {
    dynamic_column_error_message(rc);
    null_value= 1;
    return 1;
  }

  null_value= 0;
  return 0;                                     // ok
}


String *Item_dyncol_get::val_str(String *str_result)
{
  DYNAMIC_COLUMN_VALUE val;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmp(buff, sizeof(buff), &my_charset_bin);

  if (get_dyn_value(&val, &tmp))
    return NULL;

  switch (val.type) {
  case DYN_COL_NULL:
    goto null;
  case DYN_COL_INT:
  case DYN_COL_UINT:
4152
    str_result->set_int(val.x.long_value, test(val.type == DYN_COL_UINT),
4153 4154 4155
                       &my_charset_latin1);
    break;
  case DYN_COL_DOUBLE:
4156
    str_result->set_real(val.x.double_value, NOT_FIXED_DEC, &my_charset_latin1);
4157 4158
    break;
  case DYN_COL_STRING:
4159 4160
    if ((char*) tmp.ptr() <= val.x.string.value.str &&
        (char*) tmp.ptr() + tmp.length() >= val.x.string.value.str)
4161 4162
    {
      /* value is allocated in tmp buffer; We have to make a copy */
4163 4164
      str_result->copy(val.x.string.value.str, val.x.string.value.length,
                      val.x.string.charset);
4165 4166 4167 4168 4169 4170 4171 4172
    }
    else
    {
      /*
        It's safe to use the current value because it's either pointing
        into a field or in a buffer for another item and this buffer
        is not going to be deleted during expression evaluation
      */
4173 4174
      str_result->set(val.x.string.value.str, val.x.string.value.length,
                      val.x.string.charset);
4175 4176 4177 4178 4179
    }
    break;
  case DYN_COL_DECIMAL:
  {
    int res;
4180
    int length= decimal_string_size(&val.x.decimal.value);
4181 4182
    if (str_result->alloc(length))
      goto null;
4183
    if ((res= decimal2string(&val.x.decimal.value, (char*) str_result->ptr(),
4184 4185 4186 4187 4188
                             &length, 0, 0, ' ')) != E_DEC_OK)
    {
      char buff[40];
      int len= sizeof(buff);
      DBUG_ASSERT(length < (int)sizeof(buff));
4189
      decimal2string(&val.x.decimal.value, buff, &len, 0, 0, ' ');
4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200
      decimal_operation_results(res, buff, "CHAR");
    }
    str_result->set_charset(&my_charset_latin1);
    str_result->length(length);
    break;
  }
  case DYN_COL_DATETIME:
  case DYN_COL_DATE:
  case DYN_COL_TIME:
  {
    int length;
Michael Widenius's avatar
Michael Widenius committed
4201 4202 4203 4204 4205
    /*
      We use AUTO_SEC_PART_DIGITS here to ensure that we do not loose
      any microseconds from the data. This is safe to do as we are
      asked to return the time argument as a string.
    */
4206
    if (str_result->alloc(MAX_DATE_STRING_REP_LENGTH) ||
4207
        !(length= my_TIME_to_str(&val.x.time_value, (char*) str_result->ptr(),
Michael Widenius's avatar
Michael Widenius committed
4208
                                 AUTO_SEC_PART_DIGITS)))
4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
      goto null;
    str_result->set_charset(&my_charset_latin1);
    str_result->length(length);
    break;
  }
  }
  return str_result;

null:
  null_value= TRUE;
  return 0;
}


longlong Item_dyncol_get::val_int()
{
  DYNAMIC_COLUMN_VALUE val;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmp(buff, sizeof(buff), &my_charset_bin);

  if (get_dyn_value(&val, &tmp))
    return 0;

  switch (val.type) {
  case DYN_COL_NULL:
    goto null;
  case DYN_COL_UINT:
    unsigned_flag= 1;            // Make it possible for caller to detect sign
4237
    return val.x.long_value;
4238 4239
  case DYN_COL_INT:
    unsigned_flag= 0;            // Make it possible for caller to detect sign
4240
    return val.x.long_value;
4241 4242 4243 4244 4245
  case DYN_COL_DOUBLE:
  {
    bool error;
    longlong num;

4246
    num= double_to_longlong(val.x.double_value, unsigned_flag, &error);
4247 4248 4249
    if (error)
    {
      char buff[30];
4250
      sprintf(buff, "%lg", val.x.double_value);
4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                          ER_DATA_OVERFLOW,
                          ER(ER_DATA_OVERFLOW),
                          buff,
                          unsigned_flag ? "UNSIGNED INT" : "INT");
    }
    return num;
  }
  case DYN_COL_STRING:
  {
    int error;
    longlong num;
4263
    char *end= val.x.string.value.str + val.x.string.value.length, *org_end= end;
4264

4265
    num= my_strtoll10(val.x.string.value.str, &end, &error);
4266 4267 4268
    if (end != org_end || error > 0)
    {
      char buff[80];
4269 4270
      strmake(buff, val.x.string.value.str, min(sizeof(buff)-1,
                                              val.x.string.value.length));
4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                          ER_BAD_DATA,
                          ER(ER_BAD_DATA),
                          buff,
                          unsigned_flag ? "UNSIGNED INT" : "INT");
    }
    unsigned_flag= error >= 0;
    return num;
  }
  case DYN_COL_DECIMAL:
  {
    longlong num;
4283
    my_decimal2int(E_DEC_FATAL_ERROR, &val.x.decimal.value, unsigned_flag,
4284 4285 4286 4287 4288 4289
                   &num);
    return num;
  }
  case DYN_COL_DATETIME:
  case DYN_COL_DATE:
  case DYN_COL_TIME:
4290
    unsigned_flag= !val.x.time_value.neg;
Sergei Golubchik's avatar
Sergei Golubchik committed
4291
    if (unsigned_flag)
4292
      return TIME_to_ulonglong(&val.x.time_value);
Sergei Golubchik's avatar
Sergei Golubchik committed
4293
    else
4294
      return -(longlong)TIME_to_ulonglong(&val.x.time_value);
4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315
  }

null:
  null_value= TRUE;
  return 0;
}


double Item_dyncol_get::val_real()
{
  DYNAMIC_COLUMN_VALUE val;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmp(buff, sizeof(buff), &my_charset_bin);

  if (get_dyn_value(&val, &tmp))
    return 0.0;

  switch (val.type) {
  case DYN_COL_NULL:
    goto null;
  case DYN_COL_UINT:
4316
    return ulonglong2double(val.x.ulong_value);
4317
  case DYN_COL_INT:
4318
    return (double) val.x.long_value;
4319
  case DYN_COL_DOUBLE:
4320
    return (double) val.x.double_value;
4321 4322 4323 4324
  case DYN_COL_STRING:
  {
    int error;
    char *end;
4325 4326
    double res= my_strntod(val.x.string.charset, (char*) val.x.string.value.str,
                           val.x.string.value.length, &end, &error);
4327

4328
    if (end != (char*) val.x.string.value.str + val.x.string.value.length ||
4329 4330 4331
        error)
    {
      char buff[80];
4332 4333
      strmake(buff, val.x.string.value.str, min(sizeof(buff)-1,
                                              val.x.string.value.length));
4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                          ER_BAD_DATA,
                          ER(ER_BAD_DATA),
                          buff, "DOUBLE");
    }
    return res;
  }
  case DYN_COL_DECIMAL:
  {
    double res;
    /* This will always succeed */
4345
    decimal2double(&val.x.decimal.value, &res);
4346 4347 4348 4349 4350
    return res;
  }
  case DYN_COL_DATETIME:
  case DYN_COL_DATE:
  case DYN_COL_TIME:
4351
    return TIME_to_double(&val.x.time_value);
4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372
  }

null:
  null_value= TRUE;
  return 0.0;
}


my_decimal *Item_dyncol_get::val_decimal(my_decimal *decimal_value)
{
  DYNAMIC_COLUMN_VALUE val;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmp(buff, sizeof(buff), &my_charset_bin);

  if (get_dyn_value(&val, &tmp))
    return NULL;

  switch (val.type) {
  case DYN_COL_NULL:
    goto null;
  case DYN_COL_UINT:
4373
    int2my_decimal(E_DEC_FATAL_ERROR, val.x.long_value, TRUE, decimal_value);
4374 4375
    break;
  case DYN_COL_INT:
4376
    int2my_decimal(E_DEC_FATAL_ERROR, val.x.long_value, FALSE, decimal_value);
4377 4378
    break;
  case DYN_COL_DOUBLE:
4379
    double2my_decimal(E_DEC_FATAL_ERROR, val.x.double_value, decimal_value);
4380 4381 4382 4383
    break;
  case DYN_COL_STRING:
  {
    int rc;
4384 4385
    rc= str2my_decimal(0, val.x.string.value.str, val.x.string.value.length,
                       val.x.string.charset, decimal_value);
4386
    char buff[80];
4387 4388
    strmake(buff, val.x.string.value.str, min(sizeof(buff)-1,
                                            val.x.string.value.length));
4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
    if (rc != E_DEC_OK)
    {
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                          ER_BAD_DATA,
                          ER(ER_BAD_DATA),
                          buff, "DECIMAL");
    }
    break;
  }
  case DYN_COL_DECIMAL:
4399
    decimal2my_decimal(&val.x.decimal.value, decimal_value);
4400 4401 4402 4403
    break;
  case DYN_COL_DATETIME:
  case DYN_COL_DATE:
  case DYN_COL_TIME:
4404 4405 4406
    decimal_value= seconds2my_decimal(val.x.time_value.neg,
                                      TIME_to_ulonglong(&val.x.time_value),
                                      val.x.time_value.second_part,
Sergei Golubchik's avatar
Sergei Golubchik committed
4407
                                      decimal_value);
4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
    break;
  }
  return decimal_value;

null:
  null_value= TRUE;
  return 0;
}


4418
bool Item_dyncol_get::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
4419 4420 4421 4422 4423 4424 4425
{
  DYNAMIC_COLUMN_VALUE val;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmp(buff, sizeof(buff), &my_charset_bin);
  bool signed_value= 0;

  if (get_dyn_value(&val, &tmp))
4426
    return 1;                                   // Error
4427 4428 4429 4430 4431 4432

  switch (val.type) {
  case DYN_COL_NULL:
    goto null;
  case DYN_COL_INT:
    signed_value= 1;                                  // For error message
4433
    /* fall through */
4434
  case DYN_COL_UINT:
4435
    if (signed_value || val.x.ulong_value <= LONGLONG_MAX)
4436
    {
4437 4438 4439 4440
      bool neg= val.x.ulong_value > LONGLONG_MAX;
      if (int_to_datetime_with_warn(neg, neg ? -val.x.ulong_value :
                                                val.x.ulong_value,
                                    ltime, fuzzy_date, 0 /* TODO */))
Sergei Golubchik's avatar
Sergei Golubchik committed
4441 4442
        goto null;
      return 0;
4443
    }
Sergei Golubchik's avatar
Sergei Golubchik committed
4444
    /* let double_to_datetime_with_warn() issue the warning message */
4445
    val.x.double_value= static_cast<double>(ULONGLONG_MAX);
4446
    /* fall through */
4447
  case DYN_COL_DOUBLE:
4448
    if (double_to_datetime_with_warn(val.x.double_value, ltime, fuzzy_date,
Sergei Golubchik's avatar
Sergei Golubchik committed
4449
                                     0 /* TODO */))
4450 4451 4452
      goto null;
    return 0;
  case DYN_COL_DECIMAL:
4453
    if (decimal_to_datetime_with_warn((my_decimal*)&val.x.decimal.value, ltime,
Sergei Golubchik's avatar
Sergei Golubchik committed
4454
                                      fuzzy_date, 0 /* TODO */))
4455 4456 4457
      goto null;
    return 0;
  case DYN_COL_STRING:
Sergei Golubchik's avatar
Sergei Golubchik committed
4458
    if (str_to_datetime_with_warn(&my_charset_numeric,
Sergei Golubchik's avatar
Sergei Golubchik committed
4459
                                  val.x.string.value.str,
4460
                                  val.x.string.value.length,
4461 4462 4463 4464 4465 4466
                                  ltime, fuzzy_date) <= MYSQL_TIMESTAMP_ERROR)
      goto null;
    return 0;
  case DYN_COL_DATETIME:
  case DYN_COL_DATE:
  case DYN_COL_TIME:
4467
    *ltime= val.x.time_value;
4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478
    return 0;
  }

null:
  null_value= TRUE;
  return 1;
}


void Item_dyncol_get::print(String *str, enum_query_type query_type)
{
4479 4480 4481 4482 4483 4484 4485 4486 4487 4488
  /*
    Parent cast doesn't exist yet, only print dynamic column name. This happens
    when called from create_func_cast() / wrong_precision_error().
  */
  if (!str->length())
  {
    args[1]->print(str, query_type);
    return;
  }

unknown's avatar
unknown committed
4489 4490 4491 4492 4493
  /* see create_func_dyncol_get */
  DBUG_ASSERT(str->length() >= 5);
  DBUG_ASSERT(strncmp(str->ptr() + str->length() - 5, "cast(", 5) == 0);

  str->length(str->length() - 5);    // removing "cast("
4494 4495 4496 4497
  str->append(STRING_WITH_LEN("column_get("));
  args[0]->print(str, query_type);
  str->append(',');
  args[1]->print(str, query_type);
unknown's avatar
unknown committed
4498
  /* let the parent cast item add " as <type>)" */
4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
}


String *Item_func_dyncol_list::val_str(String *str)
{
  uint i;
  enum enum_dyncol_func_result rc;
  DYNAMIC_ARRAY arr;
  DYNAMIC_COLUMN col;
  String *res= args[0]->val_str(str);

  if (args[0]->null_value)
    goto null;
  col.length= res->length();
  /* We do not change the string, so could do this trick */
  col.str= (char *)res->ptr();
  if ((rc= dynamic_column_list(&col, &arr)))
  {
    dynamic_column_error_message(rc);
    delete_dynamic(&arr);
    goto null;
  }

  /*
    We support elements from 0 - 65536, so max size for one element is
    6 (including ,).
  */
  if (str->alloc(arr.elements * 6))
    goto null;

  str->length(0);
  for (i= 0; i < arr.elements; i++)
  {
    str->qs_append(*dynamic_element(&arr, i, uint*));
    if (i < arr.elements - 1)
      str->qs_append(',');
  }

4537
  null_value= FALSE;
4538 4539 4540 4541 4542 4543 4544
  delete_dynamic(&arr);
  return str;

null:
  null_value= TRUE;
  return NULL;
}