log_event_client.cc 115 KB
Newer Older
1 2
/*
   Copyright (c) 2000, 2018, Oracle and/or its affiliates.
Marko Mäkelä's avatar
Marko Mäkelä committed
3
   Copyright (c) 2009, 2021, MariaDB
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   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.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
*/


#ifndef MYSQL_CLIENT
#error MYSQL_CLIENT must be defined here
#endif

#ifdef MYSQL_SERVER
#error MYSQL_SERVER must not be defined here
#endif


29 30
static bool pretty_print_str(IO_CACHE* cache, const char* str,
                              size_t len, bool identifier)
31 32
{
  const char* end = str + len;
33
  if (my_b_write_byte(cache, identifier ? '`' : '\''))
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    goto err;

  while (str < end)
  {
    char c;
    int error;

    switch ((c=*str++)) {
    case '\n': error= my_b_write(cache, (uchar*)"\\n", 2); break;
    case '\r': error= my_b_write(cache, (uchar*)"\\r", 2); break;
    case '\\': error= my_b_write(cache, (uchar*)"\\\\", 2); break;
    case '\b': error= my_b_write(cache, (uchar*)"\\b", 2); break;
    case '\t': error= my_b_write(cache, (uchar*)"\\t", 2); break;
    case '\'': error= my_b_write(cache, (uchar*)"\\'", 2); break;
    case 0   : error= my_b_write(cache, (uchar*)"\\0", 2); break;
    default:
      error= my_b_write_byte(cache, c);
      break;
    }
    if (unlikely(error))
      goto err;
  }
56
  return my_b_write_byte(cache, identifier ? '`' : '\'');
57 58 59 60 61

err:
  return 1;
}

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
/**
  Print src as an string enclosed with "'"

  @param[out] cache  IO_CACHE where the string will be printed.
  @param[in] str  the string will be printed.
  @param[in] len  length of the string.
*/
static inline bool pretty_print_str(IO_CACHE* cache, const char* str,
                                    size_t len)
{
  return pretty_print_str(cache, str, len, false);
}

/**
  Print src as an identifier enclosed with "`"

  @param[out] cache  IO_CACHE where the identifier will be printed.
  @param[in] str  the string will be printed.
  @param[in] len  length of the string.
 */
static inline bool pretty_print_identifier(IO_CACHE* cache, const char* str,
                                           size_t len)
{
  return pretty_print_str(cache, str, len, true);
}


89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

/**
  Prints a "session_var=value" string. Used by mysqlbinlog to print some SET
  commands just before it prints a query.
*/

static bool print_set_option(IO_CACHE* file, uint32 bits_changed,
                             uint32 option, uint32 flags, const char* name,
                             bool* need_comma)
{
  if (bits_changed & option)
  {
    if (*need_comma)
      if (my_b_write(file, (uchar*)", ", 2))
        goto err;
    if (my_b_printf(file, "%s=%d", name, MY_TEST(flags & option)))
      goto err;
    *need_comma= 1;
  }
  return 0;
err:
  return 1;
}


static bool hexdump_minimal_header_to_io_cache(IO_CACHE *file,
                                               my_off_t offset,
                                               uchar *ptr)
{
  DBUG_ASSERT(LOG_EVENT_MINIMAL_HEADER_LEN == 19);

  /*
    Pretty-print the first LOG_EVENT_MINIMAL_HEADER_LEN (19) bytes of the
    common header, which contains the basic information about the log event.
    Every event will have at least this much header, but events could contain
    more headers (which must be printed by other methods, if desired).
  */
  char emit_buf[120];               // Enough for storing one line
  size_t emit_buf_written;

  if (my_b_printf(file,
                  "#           "
                  "|Timestamp   "
                  "|Type "
                  "|Master ID   "
                  "|Size        "
                  "|Master Pos  "
                  "|Flags\n"))
    goto err;
  emit_buf_written=
    my_snprintf(emit_buf, sizeof(emit_buf),
                "# %8llx  "                         /* Position */
                "|%02x %02x %02x %02x "             /* Timestamp */
                "|%02x   "                          /* Type */
                "|%02x %02x %02x %02x "             /* Master ID */
                "|%02x %02x %02x %02x "             /* Size */
                "|%02x %02x %02x %02x "             /* Master Pos */
                "|%02x %02x\n",                     /* Flags */
                (ulonglong) offset,                 /* Position */
                ptr[0], ptr[1], ptr[2], ptr[3],     /* Timestamp */
                ptr[4],                             /* Type */
                ptr[5], ptr[6], ptr[7], ptr[8],     /* Master ID */
                ptr[9], ptr[10], ptr[11], ptr[12],  /* Size */
                ptr[13], ptr[14], ptr[15], ptr[16], /* Master Pos */
                ptr[17], ptr[18]);                  /* Flags */

  DBUG_ASSERT(static_cast<size_t>(emit_buf_written) < sizeof(emit_buf));
  if (my_b_write(file, reinterpret_cast<uchar*>(emit_buf), emit_buf_written) ||
      my_b_write(file, (uchar*)"#\n", 2))
    goto err;

  return 0;
err:
  return 1;
}


/*
  The number of bytes to print per line. Should be an even number,
  and "hexdump -C" uses 16, so we'll duplicate that here.
*/
#define HEXDUMP_BYTES_PER_LINE 16

static void format_hex_line(char *emit_buff)
{
  memset(emit_buff + 1, ' ',
         1 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 2 +
         HEXDUMP_BYTES_PER_LINE);
  emit_buff[0]= '#';
  emit_buff[2 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 1]= '|';
  emit_buff[2 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 2 +
    HEXDUMP_BYTES_PER_LINE]= '|';
  emit_buff[2 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 2 +
    HEXDUMP_BYTES_PER_LINE + 1]= '\n';
  emit_buff[2 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 2 +
    HEXDUMP_BYTES_PER_LINE + 2]= '\0';
}

static bool hexdump_data_to_io_cache(IO_CACHE *file,
                                     my_off_t offset,
                                     uchar *ptr,
                                     my_off_t size)
{
  /*
    2 = '# '
    8 = address
    2 = '  '
    (HEXDUMP_BYTES_PER_LINE * 3 + 1) = Each byte prints as two hex digits,
       plus a space
    2 = ' |'
    HEXDUMP_BYTES_PER_LINE = text representation
    2 = '|\n'
    1 = '\0'
  */
  char emit_buffer[2 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 2 +
    HEXDUMP_BYTES_PER_LINE + 2 + 1 ];
  char *h,*c;
  my_off_t i;

  if (size == 0)
    return 0;                                   // ok, nothing to do

  format_hex_line(emit_buffer);
  /*
    Print the rest of the event (without common header)
  */
  my_off_t starting_offset = offset;
  for (i= 0,
       c= emit_buffer + 2 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 2,
       h= emit_buffer + 2 + 8 + 2;
       i < size;
       i++, ptr++)
  {
    my_snprintf(h, 4, "%02x ", *ptr);
    h+= 3;

    *c++= my_isprint(&my_charset_bin, *ptr) ? *ptr : '.';

    /* Print in groups of HEXDUMP_BYTES_PER_LINE characters. */
    if ((i % HEXDUMP_BYTES_PER_LINE) == (HEXDUMP_BYTES_PER_LINE - 1))
    {
      /* remove \0 left after printing hex byte representation */
      *h= ' ';
      /* prepare space to print address */
      memset(emit_buffer + 2, ' ', 8);
      /* print address */
      size_t const emit_buf_written= my_snprintf(emit_buffer + 2, 9, "%8llx",
                                                 (ulonglong) starting_offset);
      /* remove \0 left after printing address */
      emit_buffer[2 + emit_buf_written]= ' ';
      if (my_b_write(file, reinterpret_cast<uchar*>(emit_buffer),
                     sizeof(emit_buffer) - 1))
        goto err;
      c= emit_buffer + 2 + 8 + 2 + (HEXDUMP_BYTES_PER_LINE * 3 + 1) + 2;
      h= emit_buffer + 2 + 8 + 2;
      format_hex_line(emit_buffer);
      starting_offset+= HEXDUMP_BYTES_PER_LINE;
    }
    else if ((i % (HEXDUMP_BYTES_PER_LINE / 2))
             == ((HEXDUMP_BYTES_PER_LINE / 2) - 1))
    {
      /*
        In the middle of the group of HEXDUMP_BYTES_PER_LINE, emit an extra
        space in the hex string, to make two groups.
      */
      *h++= ' ';
    }

  }

  /*
    There is still data left in our buffer, which means that the previous
    line was not perfectly HEXDUMP_BYTES_PER_LINE characters, so write an
    incomplete line, with spaces to pad out to the same length as a full
    line would be, to make things more readable.
  */
  if (h != emit_buffer + 2 + 8 + 2)
  {
    *h= ' ';
    *c++= '|'; *c++= '\n';
    memset(emit_buffer + 2, ' ', 8);
    size_t const emit_buf_written= my_snprintf(emit_buffer + 2, 9, "%8llx",
                                               (ulonglong) starting_offset);
    emit_buffer[2 + emit_buf_written]= ' ';
    /* pad unprinted area */
    memset(h, ' ',
           (HEXDUMP_BYTES_PER_LINE * 3 + 1) - (h - (emit_buffer + 2 + 8 + 2)));
    if (my_b_write(file, reinterpret_cast<uchar*>(emit_buffer),
                   c - emit_buffer))
      goto err;
  }
  if (my_b_write(file, (uchar*)"#\n", 2))
    goto err;

  return 0;
err:
  return 1;
}

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
static inline bool is_numeric_type(uint type)
{
  switch (type)
  {
  case MYSQL_TYPE_TINY:
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_INT24:
  case MYSQL_TYPE_LONG:
  case MYSQL_TYPE_LONGLONG:
  case MYSQL_TYPE_NEWDECIMAL:
  case MYSQL_TYPE_FLOAT:
  case MYSQL_TYPE_DOUBLE:
    return true;
  default:
    return false;
  }
  return false;
}

static inline bool is_character_type(uint type)
{
  switch (type)
  {
  case MYSQL_TYPE_STRING:
  case MYSQL_TYPE_VAR_STRING:
  case MYSQL_TYPE_VARCHAR:
  case MYSQL_TYPE_BLOB:
  // Base class is blob for geom type
  case MYSQL_TYPE_GEOMETRY:
    return true;
  default:
    return false;
  }
}

static inline bool is_enum_or_set_type(uint type) {
  return type == MYSQL_TYPE_ENUM || type == MYSQL_TYPE_SET;
}


328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 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 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 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
/*
  Log_event::print_header()
*/

bool Log_event::print_header(IO_CACHE* file,
                             PRINT_EVENT_INFO* print_event_info,
                             bool is_more __attribute__((unused)))
{
  char llbuff[22];
  my_off_t hexdump_from= print_event_info->hexdump_from;
  DBUG_ENTER("Log_event::print_header");

  if (my_b_write_byte(file, '#') ||
      print_timestamp(file) ||
      my_b_printf(file, " server id %lu  end_log_pos %s ", (ulong) server_id,
                  llstr(log_pos,llbuff)))
    goto err;

  /* print the checksum */

  if (checksum_alg != BINLOG_CHECKSUM_ALG_OFF &&
      checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF)
  {
    char checksum_buf[BINLOG_CHECKSUM_LEN * 2 + 4]; // to fit to "%p "
    size_t const bytes_written=
      my_snprintf(checksum_buf, sizeof(checksum_buf), "0x%08x ", crc);
    if (my_b_printf(file, "%s ", get_type(&binlog_checksum_typelib,
                                          checksum_alg)) ||
        my_b_printf(file, checksum_buf, bytes_written))
      goto err;
  }

  /* mysqlbinlog --hexdump */
  if (print_event_info->hexdump_from)
  {
    my_b_write_byte(file, '\n');
    uchar *ptr= (uchar*)temp_buf;
    my_off_t size= uint4korr(ptr + EVENT_LEN_OFFSET);
    my_off_t hdr_len= get_header_len(print_event_info->common_header_len);

    size-= hdr_len;

    if (my_b_printf(file, "# Position\n"))
      goto err;

    /* Write the header, nicely formatted by field. */
    if (hexdump_minimal_header_to_io_cache(file, hexdump_from, ptr))
      goto err;

    ptr+= hdr_len;
    hexdump_from+= hdr_len;

    /* Print the rest of the data, mimicking "hexdump -C" output. */
    if (hexdump_data_to_io_cache(file, hexdump_from, ptr, size))
      goto err;

    /*
      Prefix the next line so that the output from print_helper()
      will appear as a comment.
    */
    if (my_b_write(file, (uchar*)"# Event: ", 9))
      goto err;
  }

  DBUG_RETURN(0);

err:
  DBUG_RETURN(1);
}


/**
  Prints a quoted string to io cache.
  Control characters are displayed as hex sequence, e.g. \x00
  Single-quote and backslash characters are escaped with a \

  @param[in] file              IO cache
  @param[in] prt               Pointer to string
  @param[in] length            String length
*/

static void
my_b_write_quoted(IO_CACHE *file, const uchar *ptr, uint length)
{
  const uchar *s;
  my_b_write_byte(file, '\'');
  for (s= ptr; length > 0 ; s++, length--)
  {
    if (*s > 0x1F)
      my_b_write_byte(file, *s);
    else if (*s == '\'')
      my_b_write(file, (uchar*)"\\'", 2);
    else if (*s == '\\')
      my_b_write(file, (uchar*)"\\\\", 2);
    else
    {
      uchar hex[10];
      size_t len= my_snprintf((char*) hex, sizeof(hex), "%s%02x", "\\x", *s);
      my_b_write(file, hex, len);
    }
  }
  my_b_write_byte(file, '\'');
}


/**
  Prints a bit string to io cache in format  b'1010'.
  
  @param[in] file              IO cache
  @param[in] ptr               Pointer to string
  @param[in] nbits             Number of bits
*/
static void
my_b_write_bit(IO_CACHE *file, const uchar *ptr, uint nbits)
{
  uint bitnum, nbits8= ((nbits + 7) / 8) * 8, skip_bits= nbits8 - nbits;
  my_b_write(file, (uchar*)"b'", 2);
  for (bitnum= skip_bits ; bitnum < nbits8; bitnum++)
  {
    int is_set= (ptr[(bitnum) / 8] >> (7 - bitnum % 8))  & 0x01;
    my_b_write_byte(file, (is_set ? '1' : '0'));
  }
  my_b_write_byte(file, '\'');
}


/**
  Prints a packed string to io cache.
  The string consists of length packed to 1 or 2 bytes,
  followed by string data itself.
  
  @param[in] file              IO cache
  @param[in] ptr               Pointer to string
  @param[in] length            String size
  
  @retval   - number of bytes scanned.
*/
static size_t
my_b_write_quoted_with_length(IO_CACHE *file, const uchar *ptr, uint length)
{
  if (length < 256)
  {
    length= *ptr;
    my_b_write_quoted(file, ptr + 1, length);
    return length + 1;
  }
  else
  {
    length= uint2korr(ptr);
    my_b_write_quoted(file, ptr + 2, length);
    return length + 2;
  }
}


/**
  Prints a 32-bit number in both signed and unsigned representation
  
  @param[in] file              IO cache
  @param[in] sl                Signed number
  @param[in] ul                Unsigned number
*/
static bool
my_b_write_sint32_and_uint32(IO_CACHE *file, int32 si, uint32 ui)
{
  bool res= my_b_printf(file, "%d", si);
  if (si < 0)
    if (my_b_printf(file, " (%u)", ui))
      res= 1;
  return res;
}


/**
  Print a packed value of the given SQL type into IO cache
  
  @param[in] file              IO cache
  @param[in] ptr               Pointer to string
  @param[in] type              Column type
  @param[in] meta              Column meta information
  @param[out] typestr          SQL type string buffer (for verbose output)
  @param[out] typestr_length   Size of typestr
  
  @retval   - number of bytes scanned from ptr.
              Except in case of NULL, in which case we return 1 to indicate ok
*/

static size_t
log_event_print_value(IO_CACHE *file, PRINT_EVENT_INFO *print_event_info,
                      const uchar *ptr, uint type, uint meta,
                      char *typestr, size_t typestr_length)
{
  uint32 length= 0;

  if (type == MYSQL_TYPE_STRING)
  {
    if (meta >= 256)
    {
      uint byte0= meta >> 8;
      uint byte1= meta & 0xFF;
      
      if ((byte0 & 0x30) != 0x30)
      {
        /* a long CHAR() field: see #37426 */
        length= byte1 | (((byte0 & 0x30) ^ 0x30) << 4);
        type= byte0 | 0x30;
      }
      else
        length = meta & 0xFF;
    }
    else
      length= meta;
  }

  switch (type) {
  case MYSQL_TYPE_LONG:
    {
      strmake(typestr, "INT", typestr_length);
      if (!ptr)
        goto return_null;

      int32 si= sint4korr(ptr);
      uint32 ui= uint4korr(ptr);
      my_b_write_sint32_and_uint32(file, si, ui);
      return 4;
    }

  case MYSQL_TYPE_TINY:
    {
      strmake(typestr, "TINYINT", typestr_length);
      if (!ptr)
        goto return_null;

      my_b_write_sint32_and_uint32(file, (int) (signed char) *ptr,
                                  (uint) (unsigned char) *ptr);
      return 1;
    }

  case MYSQL_TYPE_SHORT:
    {
      strmake(typestr, "SHORTINT", typestr_length);
      if (!ptr)
        goto return_null;

      int32 si= (int32) sint2korr(ptr);
      uint32 ui= (uint32) uint2korr(ptr);
      my_b_write_sint32_and_uint32(file, si, ui);
      return 2;
    }
  
  case MYSQL_TYPE_INT24:
    {
      strmake(typestr, "MEDIUMINT", typestr_length);
      if (!ptr)
        goto return_null;

      int32 si= sint3korr(ptr);
      uint32 ui= uint3korr(ptr);
      my_b_write_sint32_and_uint32(file, si, ui);
      return 3;
    }

  case MYSQL_TYPE_LONGLONG:
    {
      strmake(typestr, "LONGINT", typestr_length);
      if (!ptr)
        goto return_null;

      char tmp[64];
      size_t length;
      longlong si= sint8korr(ptr);
      length= (longlong10_to_str(si, tmp, -10) - tmp);
      my_b_write(file, (uchar*)tmp, length);
      if (si < 0)
      {
        ulonglong ui= uint8korr(ptr);
        longlong10_to_str((longlong) ui, tmp, 10);
        my_b_printf(file, " (%s)", tmp);        
      }
      return 8;
    }

  case MYSQL_TYPE_NEWDECIMAL:
    {
      uint precision= meta >> 8;
      uint decimals= meta & 0xFF;
      my_snprintf(typestr, typestr_length, "DECIMAL(%d,%d)",
                  precision, decimals);
      if (!ptr)
        goto return_null;

      uint bin_size= my_decimal_get_binary_size(precision, decimals);
      my_decimal dec((const uchar *) ptr, precision, decimals);
      int length= DECIMAL_MAX_STR_LENGTH;
      char buff[DECIMAL_MAX_STR_LENGTH + 1];
      decimal2string(&dec, buff, &length, 0, 0, 0);
      my_b_write(file, (uchar*)buff, length);
      return bin_size;
    }

  case MYSQL_TYPE_FLOAT:
    {
      strmake(typestr, "FLOAT", typestr_length);
      if (!ptr)
        goto return_null;

      float fl;
      float4get(fl, ptr);
      char tmp[320];
      sprintf(tmp, "%-20g", (double) fl);
      my_b_printf(file, "%s", tmp); /* my_snprintf doesn't support %-20g */
      return 4;
    }

  case MYSQL_TYPE_DOUBLE:
    {
      double dbl;
      strmake(typestr, "DOUBLE", typestr_length);
      if (!ptr)
        goto return_null;

      float8get(dbl, ptr);
      char tmp[320];
      sprintf(tmp, "%-.20g", dbl); /* strmake doesn't support %-20g */
      my_b_printf(file, tmp, "%s");
      return 8;
    }
  
  case MYSQL_TYPE_BIT:
    {
      /* Meta-data: bit_len, bytes_in_rec, 2 bytes */
      uint nbits= ((meta >> 8) * 8) + (meta & 0xFF);
      my_snprintf(typestr, typestr_length, "BIT(%d)", nbits);
      if (!ptr)
        goto return_null;

      length= (nbits + 7) / 8;
      my_b_write_bit(file, ptr, nbits);
      return length;
    }

  case MYSQL_TYPE_TIMESTAMP:
    {
      strmake(typestr, "TIMESTAMP", typestr_length);
      if (!ptr)
        goto return_null;

      uint32 i32= uint4korr(ptr);
      my_b_printf(file, "%d", i32);
      return 4;
    }

  case MYSQL_TYPE_TIMESTAMP2:
    {
      my_snprintf(typestr, typestr_length, "TIMESTAMP(%d)", meta);
      if (!ptr)
        goto return_null;

      char buf[MAX_DATE_STRING_REP_LENGTH];
      struct timeval tm;
      my_timestamp_from_binary(&tm, ptr, meta);
      int buflen= my_timeval_to_str(&tm, buf, meta);
      my_b_write(file, (uchar*)buf, buflen);
      return my_timestamp_binary_length(meta);
    }

  case MYSQL_TYPE_DATETIME:
    {
      strmake(typestr, "DATETIME", typestr_length);
      if (!ptr)
        goto return_null;

      ulong d, t;
      uint64 i64= uint8korr(ptr); /* YYYYMMDDhhmmss */
      d= (ulong) (i64 / 1000000);
      t= (ulong) (i64 % 1000000);

      my_b_printf(file, "'%04d-%02d-%02d %02d:%02d:%02d'",
                  (int) (d / 10000), (int) (d % 10000) / 100, (int) (d % 100),
                  (int) (t / 10000), (int) (t % 10000) / 100, (int) t % 100);
      return 8;
    }

  case MYSQL_TYPE_DATETIME2:
    {
      my_snprintf(typestr, typestr_length, "DATETIME(%d)", meta);
      if (!ptr)
        goto return_null;

      char buf[MAX_DATE_STRING_REP_LENGTH];
      MYSQL_TIME ltime;
      longlong packed= my_datetime_packed_from_binary(ptr, meta);
      TIME_from_longlong_datetime_packed(&ltime, packed);
      int buflen= my_datetime_to_str(&ltime, buf, meta);
      my_b_write_quoted(file, (uchar *) buf, buflen);
      return my_datetime_binary_length(meta);
    }

  case MYSQL_TYPE_TIME:
    {
      strmake(typestr, "TIME",  typestr_length);
      if (!ptr)
        goto return_null;

      int32 tmp= sint3korr(ptr);
      int32 i32= tmp >= 0 ? tmp : - tmp;
      const char *sign= tmp < 0 ? "-" : "";
      my_b_printf(file, "'%s%02d:%02d:%02d'",
                  sign, i32 / 10000, (i32 % 10000) / 100, i32 % 100, i32);
      return 3;
    }

  case MYSQL_TYPE_TIME2:
    {
      my_snprintf(typestr, typestr_length, "TIME(%d)", meta);
      if (!ptr)
        goto return_null;

      char buf[MAX_DATE_STRING_REP_LENGTH];
      MYSQL_TIME ltime;
      longlong packed= my_time_packed_from_binary(ptr, meta);
      TIME_from_longlong_time_packed(&ltime, packed);
      int buflen= my_time_to_str(&ltime, buf, meta);
      my_b_write_quoted(file, (uchar *) buf, buflen);
      return my_time_binary_length(meta);
    }

  case MYSQL_TYPE_NEWDATE:
    {
      strmake(typestr, "DATE", typestr_length);
      if (!ptr)
        goto return_null;

      uint32 tmp= uint3korr(ptr);
      int part;
      char buf[11];
      char *pos= &buf[10];  // start from '\0' to the beginning

      /* Copied from field.cc */
      *pos--=0;					// End NULL
      part=(int) (tmp & 31);
      *pos--= (char) ('0'+part%10);
      *pos--= (char) ('0'+part/10);
      *pos--= ':';
      part=(int) (tmp >> 5 & 15);
      *pos--= (char) ('0'+part%10);
      *pos--= (char) ('0'+part/10);
      *pos--= ':';
      part=(int) (tmp >> 9);
      *pos--= (char) ('0'+part%10); part/=10;
      *pos--= (char) ('0'+part%10); part/=10;
      *pos--= (char) ('0'+part%10); part/=10;
      *pos=   (char) ('0'+part);
      my_b_printf(file , "'%s'", buf);
      return 3;
    }
    
  case MYSQL_TYPE_DATE:
    {
      strmake(typestr, "DATE", typestr_length);
      if (!ptr)
        goto return_null;

      uint i32= uint3korr(ptr);
      my_b_printf(file , "'%04d:%02d:%02d'",
                  (int)(i32 / (16L * 32L)), (int)(i32 / 32L % 16L),
                  (int)(i32 % 32L));
      return 3;
    }
  
  case MYSQL_TYPE_YEAR:
    {
      strmake(typestr, "YEAR", typestr_length);
      if (!ptr)
        goto return_null;

      uint32 i32= *ptr;
      my_b_printf(file, "%04d", i32+ 1900);
      return 1;
    }
  
  case MYSQL_TYPE_ENUM:
    switch (meta & 0xFF) {
    case 1:
      strmake(typestr, "ENUM(1 byte)", typestr_length);
      if (!ptr)
        goto return_null;

      my_b_printf(file, "%d", (int) *ptr);
      return 1;
    case 2:
      {
        strmake(typestr, "ENUM(2 bytes)", typestr_length);
        if (!ptr)
          goto return_null;

        int32 i32= uint2korr(ptr);
        my_b_printf(file, "%d", i32);
        return 2;
      }
    default:
      my_b_printf(file, "!! Unknown ENUM packlen=%d", meta & 0xFF); 
      return 0;
    }
    break;
    
  case MYSQL_TYPE_SET:
    my_snprintf(typestr, typestr_length, "SET(%d bytes)", meta & 0xFF);
      if (!ptr)
        goto return_null;

    my_b_write_bit(file, ptr , (meta & 0xFF) * 8);
    return meta & 0xFF;
  
Marko Mäkelä's avatar
Marko Mäkelä committed
842
  case MYSQL_TYPE_BLOB_COMPRESSED:
843 844 845
  case MYSQL_TYPE_BLOB:
    switch (meta) {
    case 1:
Marko Mäkelä's avatar
Marko Mäkelä committed
846 847
      my_snprintf(typestr, typestr_length, "TINYBLOB/TINYTEXT%s",
          type == MYSQL_TYPE_BLOB_COMPRESSED ? " COMPRESSED" : "");
848 849 850 851 852 853 854
      if (!ptr)
        goto return_null;

      length= *ptr;
      my_b_write_quoted(file, ptr + 1, length);
      return length + 1;
    case 2:
Marko Mäkelä's avatar
Marko Mäkelä committed
855 856
      my_snprintf(typestr, typestr_length, "BLOB/TEXT%s",
          type == MYSQL_TYPE_BLOB_COMPRESSED ? " COMPRESSED" : "");
857 858 859 860 861 862 863
      if (!ptr)
        goto return_null;

      length= uint2korr(ptr);
      my_b_write_quoted(file, ptr + 2, length);
      return length + 2;
    case 3:
Marko Mäkelä's avatar
Marko Mäkelä committed
864 865
      my_snprintf(typestr, typestr_length, "MEDIUMBLOB/MEDIUMTEXT%s",
          type == MYSQL_TYPE_BLOB_COMPRESSED ? " COMPRESSED" : "");
866 867 868 869 870 871 872
      if (!ptr)
        goto return_null;

      length= uint3korr(ptr);
      my_b_write_quoted(file, ptr + 3, length);
      return length + 3;
    case 4:
Marko Mäkelä's avatar
Marko Mäkelä committed
873 874
      my_snprintf(typestr, typestr_length, "LONGBLOB/LONGTEXT%s",
          type == MYSQL_TYPE_BLOB_COMPRESSED ? " COMPRESSED" : "");
875 876 877 878 879 880 881 882 883 884 885
      if (!ptr)
        goto return_null;

      length= uint4korr(ptr);
      my_b_write_quoted(file, ptr + 4, length);
      return length + 4;
    default:
      my_b_printf(file, "!! Unknown BLOB packlen=%d", length);
      return 0;
    }

Marko Mäkelä's avatar
Marko Mäkelä committed
886
  case MYSQL_TYPE_VARCHAR_COMPRESSED:
887 888 889
  case MYSQL_TYPE_VARCHAR:
  case MYSQL_TYPE_VAR_STRING:
    length= meta;
Marko Mäkelä's avatar
Marko Mäkelä committed
890 891
    my_snprintf(typestr, typestr_length, "VARSTRING(%d)%s", length,
          type == MYSQL_TYPE_VARCHAR_COMPRESSED ? " COMPRESSED" : "");
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    if (!ptr)
      goto return_null;

    return my_b_write_quoted_with_length(file, ptr, length);

  case MYSQL_TYPE_STRING:
    my_snprintf(typestr, typestr_length, "STRING(%d)", length);
    if (!ptr)
      goto return_null;

    return my_b_write_quoted_with_length(file, ptr, length);

  case MYSQL_TYPE_DECIMAL:
    print_event_info->flush_for_error();
    fprintf(stderr, "\nError: Found Old DECIMAL (mysql-4.1 or earlier). "
            "Not enough metadata to display the value.\n");
    break;
Sujatha's avatar
Sujatha committed
909 910 911 912 913 914 915 916 917 918

  case MYSQL_TYPE_GEOMETRY:
    strmake(typestr, "GEOMETRY", typestr_length);
    if (!ptr)
      goto return_null;

    length= uint4korr(ptr);
    my_b_write_quoted(file, ptr + meta, length);
    return length + meta;

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  default:
    print_event_info->flush_for_error();
    fprintf(stderr,
            "\nError: Don't know how to handle column type: %d meta: %d (%04x)\n",
            type, meta, meta);
    break;
  }
  *typestr= 0;
  return 0;

return_null:
  return my_b_write(file, (uchar*) "NULL", 4) ? 0 : 1;
}


/**
  Print a packed row into IO cache
  
  @param[in] file              IO cache
  @param[in] td                Table definition
  @param[in] print_event_into  Print parameters
  @param[in] cols_bitmap       Column bitmaps.
  @param[in] value             Pointer to packed row
  @param[in] prefix            Row's SQL clause ("SET", "WHERE", etc)
  
  @retval   0 error
            # number of bytes scanned.
*/


size_t
Rows_log_event::print_verbose_one_row(IO_CACHE *file, table_def *td,
                                      PRINT_EVENT_INFO *print_event_info,
                                      MY_BITMAP *cols_bitmap,
                                      const uchar *value, const uchar *prefix,
                                      const my_bool no_fill_output)
{
  const uchar *value0= value;
  const uchar *null_bits= value;
  uint null_bit_index= 0;
  char typestr[64]= "";

#ifdef WHEN_FLASHBACK_REVIEW_READY
  /* Storing the review SQL */
  IO_CACHE *review_sql= &print_event_info->review_sql_cache;
  LEX_STRING review_str;
#endif

  /*
    Skip metadata bytes which gives the information about nullabity of master
    columns. Master writes one bit for each affected column.
   */

  value+= (bitmap_bits_set(cols_bitmap) + 7) / 8;

  if (!no_fill_output)
    if (my_b_printf(file, "%s", prefix))
      goto err;

  for (uint i= 0; i < (uint)td->size(); i ++)
  {
    size_t size;
    int is_null= (null_bits[null_bit_index / 8] 
                  >> (null_bit_index % 8))  & 0x01;

    if (bitmap_is_set(cols_bitmap, i) == 0)
      continue;

    if (!no_fill_output)
      if (my_b_printf(file, "###   @%d=", static_cast<int>(i + 1)))
        goto err;

    if (!is_null)
    {
      size_t fsize= td->calc_field_size((uint)i, (uchar*) value);
      if (value + fsize > m_rows_end)
      {
        if (!no_fill_output)
          if (my_b_printf(file, "***Corrupted replication event was detected."
                          " Not printing the value***\n"))
            goto err;
        value+= fsize;
        return 0;
      }
    }

    if (!no_fill_output)
    {
      size= log_event_print_value(file, print_event_info, is_null? NULL: value,
                                  td->type(i), td->field_metadata(i),
                                  typestr, sizeof(typestr));
#ifdef WHEN_FLASHBACK_REVIEW_READY
      if (need_flashback_review)
      {
        String tmp_str, hex_str;
        IO_CACHE tmp_cache;

        // Using a tmp IO_CACHE to get the value output
        open_cached_file(&tmp_cache, NULL, NULL, 0, MYF(MY_WME | MY_NABP));
        size= log_event_print_value(&tmp_cache, print_event_info,
                                    is_null ? NULL: value,
                                    td->type(i), td->field_metadata(i),
                                    typestr, sizeof(typestr));
        error= copy_event_cache_to_string_and_reinit(&tmp_cache, &review_str);
        close_cached_file(&tmp_cache);
        if (unlikely(error))
          return 0;

        switch (td->type(i)) // Converting a string to HEX format
        {
          case MYSQL_TYPE_VARCHAR:
          case MYSQL_TYPE_VAR_STRING:
          case MYSQL_TYPE_STRING:
          case MYSQL_TYPE_BLOB:
            // Avoid write_pos changed to a new area
            // tmp_str.free();
            tmp_str.append(review_str.str + 1, review_str.length - 2); // Removing quotation marks
            if (hex_str.alloc(tmp_str.length()*2+1)) // If out of memory
            {
              fprintf(stderr, "\nError: Out of memory. "
                      "Could not print correct binlog event.\n");
              exit(1);
            }
            octet2hex((char*) hex_str.ptr(), tmp_str.ptr(), tmp_str.length());
            if (my_b_printf(review_sql, ", UNHEX('%s')", hex_str.ptr()))
              goto err;
            break;
          default:
            tmp_str.free();
            if (tmp_str.append(review_str.str, review_str.length) ||
                my_b_printf(review_sql, ", %s", tmp_str.ptr()))
              goto err;
            break;
        }
        my_free(revieww_str.str);
      }
#endif
    }
    else
    {
      IO_CACHE tmp_cache;
      open_cached_file(&tmp_cache, NULL, NULL, 0, MYF(MY_WME | MY_NABP));
      size= log_event_print_value(&tmp_cache, print_event_info,
                                  is_null ? NULL: value,
                                  td->type(i), td->field_metadata(i),
                                  typestr, sizeof(typestr));
      close_cached_file(&tmp_cache);
    }

    if (!size)
      goto err;

    if (!is_null)
      value+= size;

    if (print_event_info->verbose > 1 && !no_fill_output)
    {
      if (my_b_write(file, (uchar*)" /* ", 4) ||
          my_b_printf(file, "%s ", typestr) ||
          my_b_printf(file, "meta=%d nullable=%d is_null=%d ",
                      td->field_metadata(i),
                      td->maybe_null(i), is_null) ||
          my_b_write(file, (uchar*)"*/", 2))
        goto err;
    }

    if (!no_fill_output)
      if (my_b_write_byte(file, '\n'))
        goto err;

    null_bit_index++;
  }
  return value - value0;

err:
  return 0;
}


/**
  Exchange the SET part and WHERE part for the Update events.
  Revert the operations order for the Write and Delete events.
  And then revert the events order from the last one to the first one.

  @param[in] print_event_info   PRINT_EVENT_INFO
  @param[in] rows_buff          Packed event buff
*/

void Rows_log_event::change_to_flashback_event(PRINT_EVENT_INFO *print_event_info,
                                               uchar *rows_buff, Log_event_type ev_type)
{
  Table_map_log_event *map;
  table_def *td;
  DYNAMIC_ARRAY rows_arr;
Marko Mäkelä's avatar
Marko Mäkelä committed
1113
  uchar *swap_buff1;
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
  uchar *rows_pos= rows_buff + m_rows_before_size;

  if (!(map= print_event_info->m_table_map.get_table(m_table_id)) ||
      !(td= map->create_table_def()))
    return;

  /* If the write rows event contained no values for the AI */
  if (((get_general_type_code() == WRITE_ROWS_EVENT) && (m_rows_buf==m_rows_end)))
    goto end;

1124
  (void) my_init_dynamic_array(PSI_NOT_INSTRUMENTED, &rows_arr, sizeof(LEX_STRING), 8, 8, MYF(0));
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

  for (uchar *value= m_rows_buf; value < m_rows_end; )
  {
    uchar *start_pos= value;
    size_t length1= 0;
    if (!(length1= print_verbose_one_row(NULL, td, print_event_info,
                                         &m_cols, value,
                                         (const uchar*) "", TRUE)))
    {
      fprintf(stderr, "\nError row length: %zu\n", length1);
      exit(1);
    }
    value+= length1;

1139
    swap_buff1= (uchar *) my_malloc(PSI_NOT_INSTRUMENTED, length1, MYF(0));
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    if (!swap_buff1)
    {
      fprintf(stderr, "\nError: Out of memory. "
              "Could not exchange to flashback event.\n");
      exit(1);
    }
    memcpy(swap_buff1, start_pos, length1);

    // For Update_event, we have the second part
    size_t length2= 0;
    if (ev_type == UPDATE_ROWS_EVENT ||
        ev_type == UPDATE_ROWS_EVENT_V1)
    {
      if (!(length2= print_verbose_one_row(NULL, td, print_event_info,
                                           &m_cols, value,
                                           (const uchar*) "", TRUE)))
      {
        fprintf(stderr, "\nError row length: %zu\n", length2);
        exit(1);
      }
      value+= length2;

Marko Mäkelä's avatar
Marko Mäkelä committed
1162
      void *swap_buff2= my_malloc(PSI_NOT_INSTRUMENTED, length2, MYF(0));
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
      if (!swap_buff2)
      {
        fprintf(stderr, "\nError: Out of memory. "
                "Could not exchange to flashback event.\n");
        exit(1);
      }
      memcpy(swap_buff2, start_pos + length1, length2); // WHERE part

      /* Swap SET and WHERE part */
      memcpy(start_pos, swap_buff2, length2);
      memcpy(start_pos + length2, swap_buff1, length1);
Marko Mäkelä's avatar
Marko Mäkelä committed
1174
      my_free(swap_buff2);
1175 1176 1177 1178 1179 1180 1181 1182
    }

    my_free(swap_buff1);

    /* Copying one row into a buff, and pushing into the array */
    LEX_STRING one_row;

    one_row.length= length1 + length2;
1183
    one_row.str=    (char *) my_malloc(PSI_NOT_INSTRUMENTED, one_row.length, MYF(0));
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    memcpy(one_row.str, start_pos, one_row.length);
    if (one_row.str == NULL || push_dynamic(&rows_arr, (uchar *) &one_row))
    {
      fprintf(stderr, "\nError: Out of memory. "
              "Could not push flashback event into array.\n");
      exit(1);
    }
  }

  /* Copying rows from the end to the begining into event */
  for (uint i= rows_arr.elements; i > 0; --i)
  {
    LEX_STRING *one_row= dynamic_element(&rows_arr, i - 1, LEX_STRING*);

    memcpy(rows_pos, (uchar *)one_row->str, one_row->length);
    rows_pos+= one_row->length;
    my_free(one_row->str);
  }
  delete_dynamic(&rows_arr);

end:
  delete td;
}

/**
  Calc length of a packed value of the given SQL type

  @param[in] ptr               Pointer to string
  @param[in] type              Column type
  @param[in] meta              Column meta information

  @retval   - number of bytes scanned from ptr.
              Except in case of NULL, in which case we return 1 to indicate ok
*/

static size_t calc_field_event_length(const uchar *ptr, uint type, uint meta)
{
  uint32 length= 0;

  if (type == MYSQL_TYPE_STRING)
  {
    if (meta >= 256)
    {
      uint byte0= meta >> 8;
      uint byte1= meta & 0xFF;

      if ((byte0 & 0x30) != 0x30)
      {
        /* a long CHAR() field: see #37426 */
        length= byte1 | (((byte0 & 0x30) ^ 0x30) << 4);
        type= byte0 | 0x30;
      }
      else
        length = meta & 0xFF;
    }
    else
      length= meta;
  }

  switch (type) {
  case MYSQL_TYPE_LONG:
  case MYSQL_TYPE_TIMESTAMP:
    return 4;
  case MYSQL_TYPE_TINY:
  case MYSQL_TYPE_YEAR:
    return 1;
  case MYSQL_TYPE_SHORT:
    return 2;
  case MYSQL_TYPE_INT24:
  case MYSQL_TYPE_TIME:
  case MYSQL_TYPE_NEWDATE:
  case MYSQL_TYPE_DATE:
      return 3;
  case MYSQL_TYPE_LONGLONG:
  case MYSQL_TYPE_DATETIME:
    return 8;
  case MYSQL_TYPE_NEWDECIMAL:
  {
    uint precision= meta >> 8;
    uint decimals= meta & 0xFF;
    uint bin_size= my_decimal_get_binary_size(precision, decimals);
    return bin_size;
  }
  case MYSQL_TYPE_FLOAT:
    return 4;
  case MYSQL_TYPE_DOUBLE:
    return 8;
  case MYSQL_TYPE_BIT:
  {
    /* Meta-data: bit_len, bytes_in_rec, 2 bytes */
    uint nbits= ((meta >> 8) * 8) + (meta & 0xFF);
    length= (nbits + 7) / 8;
    return length;
  }
  case MYSQL_TYPE_TIMESTAMP2:
    return my_timestamp_binary_length(meta);
  case MYSQL_TYPE_DATETIME2:
    return my_datetime_binary_length(meta);
  case MYSQL_TYPE_TIME2:
    return my_time_binary_length(meta);
  case MYSQL_TYPE_ENUM:
    switch (meta & 0xFF) {
    case 1:
    case 2:
      return (meta & 0xFF);
    default:
      /* Unknown ENUM packlen=%d", meta & 0xFF */
      return 0;
    }
    break;
  case MYSQL_TYPE_SET:
    return meta & 0xFF;
  case MYSQL_TYPE_BLOB:
Marko Mäkelä's avatar
Marko Mäkelä committed
1297 1298
    switch (meta) {
    default:
1299
      return 0;
Marko Mäkelä's avatar
Marko Mäkelä committed
1300
    case 1:
1301
      return *ptr + 1;
Marko Mäkelä's avatar
Marko Mäkelä committed
1302
    case 2:
1303
      return uint2korr(ptr) + 2;
Marko Mäkelä's avatar
Marko Mäkelä committed
1304
    case 3:
1305
      return uint3korr(ptr) + 3;
Marko Mäkelä's avatar
Marko Mäkelä committed
1306
    case 4:
1307
      return uint4korr(ptr) + 4;
Marko Mäkelä's avatar
Marko Mäkelä committed
1308
    }
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
  case MYSQL_TYPE_VARCHAR:
  case MYSQL_TYPE_VAR_STRING:
    length= meta;
    /* fall through */
  case MYSQL_TYPE_STRING:
    if (length < 256)
      return (uint) *ptr + 1;
    return uint2korr(ptr) + 2;
  case MYSQL_TYPE_DECIMAL:
    break;
  default:
    break;
  }
  return 0;
}


size_t
Rows_log_event::calc_row_event_length(table_def *td,
                                      PRINT_EVENT_INFO *print_event_info,
                                      MY_BITMAP *cols_bitmap,
                                      const uchar *value)
{
  const uchar *value0= value;
  const uchar *null_bits= value;
  uint null_bit_index= 0;

  /*
    Skip metadata bytes which gives the information about nullabity of master
    columns. Master writes one bit for each affected column.
   */

  value+= (bitmap_bits_set(cols_bitmap) + 7) / 8;

  for (uint i= 0; i < (uint)td->size(); i ++)
  {
    int is_null;
    is_null= (null_bits[null_bit_index / 8] >> (null_bit_index % 8)) & 0x01;

    if (bitmap_is_set(cols_bitmap, i) == 0)
      continue;

    if (!is_null)
    {
      size_t size;
      size_t fsize= td->calc_field_size((uint)i, (uchar*) value);
      if (value + fsize > m_rows_end)
      {
        /* Corrupted replication event was detected, skipping entry */
        return 0;
      }
      if (!(size= calc_field_event_length(value, td->type(i),
                                          td->field_metadata(i))))
        return 0;
      value+= size;
    }
    null_bit_index++;
  }
  return value - value0;
}


/**
   Calculate how many rows there are in the event

  @param[in] file              IO cache
  @param[in] print_event_into  Print parameters
*/

void Rows_log_event::count_row_events(PRINT_EVENT_INFO *print_event_info)
{
  Table_map_log_event *map;
  table_def *td;
  uint row_events;
  Log_event_type general_type_code= get_general_type_code();

  switch (general_type_code) {
  case WRITE_ROWS_EVENT:
  case DELETE_ROWS_EVENT:
    row_events= 1;
    break;
  case UPDATE_ROWS_EVENT:
    row_events= 2;
    break;
  default:
    DBUG_ASSERT(0); /* Not possible */
    return;
  }

  if (!(map= print_event_info->m_table_map.get_table(m_table_id)) ||
      !(td= map->create_table_def()))
  {
    /* Row event for unknown table */
    return;
  }

  for (const uchar *value= m_rows_buf; value < m_rows_end; )
  {
    size_t length;
    print_event_info->row_events++;

    /* Print the first image */
    if (!(length= calc_row_event_length(td, print_event_info,
                                        &m_cols, value)))
      break;
    value+= length;
    DBUG_ASSERT(value <= m_rows_end);

    /* Print the second image (for UPDATE only) */
    if (row_events == 2)
    {
      if (!(length= calc_row_event_length(td, print_event_info,
                                          &m_cols_ai, value)))
        break;
      value+= length;
      DBUG_ASSERT(value <= m_rows_end);
    }
  }
  delete td;
}


/**
  Print a row event into IO cache in human readable form (in SQL format)

  @param[in] file              IO cache
  @param[in] print_event_into  Print parameters
*/

bool Rows_log_event::print_verbose(IO_CACHE *file,
                                   PRINT_EVENT_INFO *print_event_info)
{
  Table_map_log_event *map;
  table_def *td= 0;
  const char *sql_command, *sql_clause1, *sql_clause2;
  const char *sql_command_short __attribute__((unused));
  Log_event_type general_type_code= get_general_type_code();
#ifdef WHEN_FLASHBACK_REVIEW_READY
  IO_CACHE *review_sql= &print_event_info->review_sql_cache;
#endif

  if (m_extra_row_data)
  {
    uint8 extra_data_len= m_extra_row_data[EXTRA_ROW_INFO_LEN_OFFSET];
    uint8 extra_payload_len= extra_data_len - EXTRA_ROW_INFO_HDR_BYTES;
    assert(extra_data_len >= EXTRA_ROW_INFO_HDR_BYTES);

    if (my_b_printf(file, "### Extra row data format: %u, len: %u :",
                    m_extra_row_data[EXTRA_ROW_INFO_FORMAT_OFFSET],
                    extra_payload_len))
      goto err;
    if (extra_payload_len)
    {
      /*
         Buffer for hex view of string, including '0x' prefix,
         2 hex chars / byte and trailing 0
      */
      const int buff_len= 2 + (256 * 2) + 1;
      char buff[buff_len];
      str_to_hex(buff, (const char*) &m_extra_row_data[EXTRA_ROW_INFO_HDR_BYTES],
                 extra_payload_len);
      if (my_b_printf(file, "%s", buff))
        goto err;
    }
    if (my_b_printf(file, "\n"))
      goto err;
  }

  switch (general_type_code) {
  case WRITE_ROWS_EVENT:
    sql_command= "INSERT INTO";
    sql_clause1= "### SET\n";
    sql_clause2= NULL;
    sql_command_short= "I";
    break;
  case DELETE_ROWS_EVENT:
    sql_command= "DELETE FROM";
    sql_clause1= "### WHERE\n";
    sql_clause2= NULL;
    sql_command_short= "D";
    break;
  case UPDATE_ROWS_EVENT:
    sql_command= "UPDATE";
    sql_clause1= "### WHERE\n";
    sql_clause2= "### SET\n";
    sql_command_short= "U";
    break;
  default:
    sql_command= sql_clause1= sql_clause2= NULL;
    sql_command_short= "";
    DBUG_ASSERT(0); /* Not possible */
  }

  if (!(map= print_event_info->m_table_map.get_table(m_table_id)) ||
      !(td= map->create_table_def()))
  {
1505 1506 1507
    char llbuff[22];
    return (my_b_printf(file, "### Row event for unknown table #%s",
                        ullstr(m_table_id, llbuff)));
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
  }

  /* If the write rows event contained no values for the AI */
  if (((general_type_code == WRITE_ROWS_EVENT) && (m_rows_buf==m_rows_end)))
  {
    if (my_b_printf(file, "### INSERT INTO %`s.%`s VALUES ()\n",
                    map->get_db_name(), map->get_table_name()))
      goto err;
    goto end;
  }

  for (const uchar *value= m_rows_buf; value < m_rows_end; )
  {
    size_t length;
    print_event_info->row_events++;

    if (my_b_printf(file, "### %s %`s.%`s\n",
                    sql_command,
                    map->get_db_name(), map->get_table_name()))
      goto err;
#ifdef WHEN_FLASHBACK_REVIEW_READY
    if (need_flashback_review)
      if (my_b_printf(review_sql, "\nINSERT INTO `%s`.`%s` VALUES ('%s'",
                      map->get_review_dbname(), map->get_review_tablename(),
                      sql_command_short))
        goto err;
#endif

    /* Print the first image */
    if (!(length= print_verbose_one_row(file, td, print_event_info,
                                  &m_cols, value,
                                  (const uchar*) sql_clause1)))
      goto err;
    value+= length;

    /* Print the second image (for UPDATE only) */
    if (sql_clause2)
    {
      if (!(length= print_verbose_one_row(file, td, print_event_info,
                                      &m_cols_ai, value,
                                      (const uchar*) sql_clause2)))
        goto err;
      value+= length;
    }
#ifdef WHEN_FLASHBACK_REVIEW_READY
    else
    {
      if (need_flashback_review)
        for (size_t i= 0; i < td->size(); i ++)
          if (my_b_printf(review_sql, ", NULL"))
            goto err;
    }

    if (need_flashback_review)
      if (my_b_printf(review_sql, ")%s\n", print_event_info->delimiter))
        goto err;
#endif
  }

end:
  delete td;
  return 0;
err:
  delete td;
  return 1;
}

void free_table_map_log_event(Table_map_log_event *event)
{
  delete event;
}

/**
  Encode the event, optionally per 'do_print_encoded' arg store the
  result into the argument cache; optionally per event_info's
  'verbose' print into the cache a verbose representation of the event.
  Note, no extra wrapping is done to the being io-cached data, like
  to producing a BINLOG query. It's left for a routine that extracts from
  the cache.

  @param file               pointer to IO_CACHE
  @param print_event_info   pointer to print_event_info specializing
                            what out of and how to print the event
  @param do_print_encoded   whether to store base64-encoded event
                            into @file.
*/
bool Log_event::print_base64(IO_CACHE* file,
                             PRINT_EVENT_INFO* print_event_info,
                             bool do_print_encoded)
{
1598
  uchar *ptr= temp_buf;
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
  uint32 size= uint4korr(ptr + EVENT_LEN_OFFSET);
  DBUG_ENTER("Log_event::print_base64");

  if (is_flashback)
  {
    uint tmp_size= size;
    Rows_log_event *ev= NULL;
    Log_event_type ev_type = (enum Log_event_type) ptr[EVENT_TYPE_OFFSET];
    if (checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF &&
        checksum_alg != BINLOG_CHECKSUM_ALG_OFF)
      tmp_size-= BINLOG_CHECKSUM_LEN; // checksum is displayed through the header
    switch (ev_type) {
      case WRITE_ROWS_EVENT:
        ptr[EVENT_TYPE_OFFSET]= DELETE_ROWS_EVENT;
1613
        ev= new Delete_rows_log_event(ptr, tmp_size,
1614 1615 1616 1617 1618
                                       glob_description_event);
        ev->change_to_flashback_event(print_event_info, ptr, ev_type);
        break;
      case WRITE_ROWS_EVENT_V1:
        ptr[EVENT_TYPE_OFFSET]= DELETE_ROWS_EVENT_V1;
1619
        ev= new Delete_rows_log_event(ptr, tmp_size,
1620 1621 1622 1623 1624
                                       glob_description_event);
        ev->change_to_flashback_event(print_event_info, ptr, ev_type);
        break;
      case DELETE_ROWS_EVENT:
        ptr[EVENT_TYPE_OFFSET]= WRITE_ROWS_EVENT;
1625
        ev= new Write_rows_log_event(ptr, tmp_size,
1626 1627 1628 1629 1630
                                       glob_description_event);
        ev->change_to_flashback_event(print_event_info, ptr, ev_type);
        break;
      case DELETE_ROWS_EVENT_V1:
        ptr[EVENT_TYPE_OFFSET]= WRITE_ROWS_EVENT_V1;
1631
        ev= new Write_rows_log_event(ptr, tmp_size,
1632 1633 1634 1635 1636
                                       glob_description_event);
        ev->change_to_flashback_event(print_event_info, ptr, ev_type);
        break;
      case UPDATE_ROWS_EVENT:
      case UPDATE_ROWS_EVENT_V1:
1637
        ev= new Update_rows_log_event(ptr, tmp_size,
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
                                       glob_description_event);
        ev->change_to_flashback_event(print_event_info, ptr, ev_type);
        break;
      default:
        break;
    }
    delete ev;
  }

  if (do_print_encoded)
  {
    size_t const tmp_str_sz= my_base64_needed_encoded_length((int) size);
    char *tmp_str;
1651
    if (!(tmp_str= (char *) my_malloc(PSI_NOT_INSTRUMENTED, tmp_str_sz, MYF(MY_WME))))
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
      goto err;

    if (my_base64_encode(ptr, (size_t) size, tmp_str))
    {
      DBUG_ASSERT(0);
    }

    my_b_printf(file, "%s\n", tmp_str);
    my_free(tmp_str);
  }

#ifdef WHEN_FLASHBACK_REVIEW_READY
  if (print_event_info->verbose || print_event_info->print_row_count ||
      need_flashback_review)
#else
  // Flashback need the table_map to parse the event
  if (print_event_info->verbose || print_event_info->print_row_count ||
      is_flashback)
#endif
  {
    Rows_log_event *ev= NULL;
    Log_event_type et= (Log_event_type) ptr[EVENT_TYPE_OFFSET];

    if (checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF &&
        checksum_alg != BINLOG_CHECKSUM_ALG_OFF)
      size-= BINLOG_CHECKSUM_LEN; // checksum is displayed through the header

    switch (et)
    {
    case TABLE_MAP_EVENT:
    {
      Table_map_log_event *map; 
1684
      map= new Table_map_log_event(ptr, size, 
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
                                   glob_description_event);
#ifdef WHEN_FLASHBACK_REVIEW_READY
      if (need_flashback_review)
      {
        map->set_review_dbname(m_review_dbname.ptr());
        map->set_review_tablename(m_review_tablename.ptr());
      }
#endif
      print_event_info->m_table_map.set_table(map->get_table_id(), map);
      break;
    }
    case WRITE_ROWS_EVENT:
    case WRITE_ROWS_EVENT_V1:
    {
1699
      ev= new Write_rows_log_event(ptr, size,
1700 1701 1702 1703 1704 1705
                                   glob_description_event);
      break;
    }
    case DELETE_ROWS_EVENT:
    case DELETE_ROWS_EVENT_V1:
    {
1706
      ev= new Delete_rows_log_event(ptr, size,
1707 1708 1709 1710 1711 1712
                                    glob_description_event);
      break;
    }
    case UPDATE_ROWS_EVENT:
    case UPDATE_ROWS_EVENT_V1:
    {
1713
      ev= new Update_rows_log_event(ptr, size,
1714 1715 1716 1717 1718 1719
                                    glob_description_event);
      break;
    }
    case WRITE_ROWS_COMPRESSED_EVENT:
    case WRITE_ROWS_COMPRESSED_EVENT_V1:
    {
1720
      ev= new Write_rows_compressed_log_event(ptr, size,
1721 1722 1723 1724 1725 1726
                                              glob_description_event);
      break;
    }
    case UPDATE_ROWS_COMPRESSED_EVENT:
    case UPDATE_ROWS_COMPRESSED_EVENT_V1:
    {
1727
      ev= new Update_rows_compressed_log_event(ptr, size,
1728 1729 1730 1731 1732 1733
                                               glob_description_event);
      break;
      }
    case DELETE_ROWS_COMPRESSED_EVENT:
    case DELETE_ROWS_COMPRESSED_EVENT_V1:
    {
1734
      ev= new Delete_rows_compressed_log_event(ptr, size,
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
                                               glob_description_event);
      break;
    }
    default:
      break;
    }

    if (ev)
    {
      bool error= 0;

#ifdef WHEN_FLASHBACK_REVIEW_READY
      ev->need_flashback_review= need_flashback_review;
      if (print_event_info->verbose)
      {
Marko Mäkelä's avatar
Marko Mäkelä committed
1750
        if (ev->print_verbose(&print_event_info->tail_cache, print_event_info))
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
          goto err;
      }
      else
      {
        IO_CACHE tmp_cache;

        if (open_cached_file(&tmp_cache, NULL, NULL, 0,
                              MYF(MY_WME | MY_NABP)))
        {
          delete ev;
          goto err;
        }

        error= ev->print_verbose(&tmp_cache, print_event_info);
        close_cached_file(&tmp_cache);
        if (unlikely(error))
        {
          delete ev;
          goto err;
        }
      }
#else
      if (print_event_info->verbose)
Marko Mäkelä's avatar
Marko Mäkelä committed
1774
        error= ev->print_verbose(&print_event_info->tail_cache, print_event_info);
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
      else
        ev->count_row_events(print_event_info);
#endif
      delete ev;
      if (unlikely(error))
        goto err;
    }
  }
  DBUG_RETURN(0);

err:
  DBUG_RETURN(1);
}


/*
  Log_event::print_timestamp()
*/

bool Log_event::print_timestamp(IO_CACHE* file, time_t* ts)
{
  struct tm *res;
  time_t my_when= when;
  DBUG_ENTER("Log_event::print_timestamp");
  if (!ts)
    ts = &my_when;
  res=localtime(ts);

  DBUG_RETURN(my_b_printf(file,"%02d%02d%02d %2d:%02d:%02d",
                          res->tm_year % 100,
                          res->tm_mon+1,
                          res->tm_mday,
                          res->tm_hour,
                          res->tm_min,
                          res->tm_sec));
}


/**
  Query_log_event::print().

  @todo
    print the catalog ??
*/
bool Query_log_event::print_query_header(IO_CACHE* file,
					 PRINT_EVENT_INFO* print_event_info)
{
  // TODO: print the catalog ??
  char buff[64], *end;				// Enough for SET TIMESTAMP
  bool different_db= 1;
  uint32 tmp;

  if (!print_event_info->short_form)
  {
    if (print_header(file, print_event_info, FALSE) ||
        my_b_printf(file,
Monty's avatar
Monty committed
1831 1832
                    "\t%s\tthread_id=%lu\texec_time=%lu\terror_code=%d"
                    "\txid=%lu\n",
1833
                    get_type_str(), (ulong) thread_id, (ulong) exec_time,
Monty's avatar
Monty committed
1834
                    error_code, (ulong) xid))
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
      goto err;
  }

  if ((flags & LOG_EVENT_SUPPRESS_USE_F))
  {
    if (!is_trans_keyword())
      print_event_info->db[0]= '\0';
  }
  else if (db)
  {
    different_db= memcmp(print_event_info->db, db, db_len + 1);
    if (different_db)
      memcpy(print_event_info->db, db, db_len + 1);
    if (db[0] && different_db) 
      if (my_b_printf(file, "use %`s%s\n", db, print_event_info->delimiter))
        goto err;
  }

  end=int10_to_str((long) when, strmov(buff,"SET TIMESTAMP="),10);
  if (when_sec_part && when_sec_part <= TIME_MAX_SECOND_PART)
  {
    *end++= '.';
    end=int10_to_str(when_sec_part, end, 10);
  }
  end= strmov(end, print_event_info->delimiter);
  *end++='\n';
  if (my_b_write(file, (uchar*) buff, (uint) (end-buff)))
    goto err;
  if ((!print_event_info->thread_id_printed ||
       ((flags & LOG_EVENT_THREAD_SPECIFIC_F) &&
        thread_id != print_event_info->thread_id)))
  {
    // If --short-form, print deterministic value instead of pseudo_thread_id.
    if (my_b_printf(file,"SET @@session.pseudo_thread_id=%lu%s\n",
                    short_form ? 999999999 : (ulong)thread_id,
                    print_event_info->delimiter))
      goto err;
    print_event_info->thread_id= thread_id;
    print_event_info->thread_id_printed= 1;
  }

  /*
1877 1878 1879 1880
    If flags2_inited==0, this is an event from 3.23 or 4.0 or a dummy
    event from the mtr test suite; nothing to print (remember we don't
    produce mixed relay logs so there cannot be 5.0 events before that
    one so there is nothing to reset).
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
  */
  if (likely(flags2_inited)) /* likely as this will mainly read 5.0 logs */
  {
    /* tmp is a bitmask of bits which have changed. */
    if (likely(print_event_info->flags2_inited)) 
      /* All bits which have changed */
      tmp= (print_event_info->flags2) ^ flags2;
    else /* that's the first Query event we read */
    {
      print_event_info->flags2_inited= 1;
      tmp= ~((uint32)0); /* all bits have changed */
    }

    if (unlikely(tmp)) /* some bits have changed */
    {
      bool need_comma= 0;
1897
      ulonglong mask= glob_description_event->options_written_to_bin_log;
1898 1899 1900 1901 1902 1903 1904 1905 1906
      if (my_b_write_string(file, "SET ") ||
          print_set_option(file, tmp, OPTION_NO_FOREIGN_KEY_CHECKS, ~flags2,
                           "@@session.foreign_key_checks", &need_comma)||
          print_set_option(file, tmp, OPTION_AUTO_IS_NULL, flags2,
                           "@@session.sql_auto_is_null", &need_comma) ||
          print_set_option(file, tmp, OPTION_RELAXED_UNIQUE_CHECKS, ~flags2,
                           "@@session.unique_checks", &need_comma) ||
          print_set_option(file, tmp, OPTION_NOT_AUTOCOMMIT, ~flags2,
                           "@@session.autocommit", &need_comma) ||
1907
          print_set_option(file, tmp, OPTION_NO_CHECK_CONSTRAINT_CHECKS, ~flags2,
1908
                           "@@session.check_constraint_checks", &need_comma) ||
1909 1910 1911 1912 1913
          print_set_option(file, tmp, mask & OPTION_IF_EXISTS, flags2,
                           "@@session.sql_if_exists", &need_comma) ||
          print_set_option(file, tmp, mask & OPTION_EXPLICIT_DEF_TIMESTAMP, flags2,
                           "@@session.explicit_defaults_for_timestamp",
                           &need_comma) ||
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
          my_b_printf(file,"%s\n", print_event_info->delimiter))
        goto err;
      print_event_info->flags2= flags2;
    }
  }

  /*
    Now the session variables;
    it's more efficient to pass SQL_MODE as a number instead of a
    comma-separated list.
    FOREIGN_KEY_CHECKS, SQL_AUTO_IS_NULL, UNIQUE_CHECKS are session-only
    variables (they have no global version; they're not listed in
    sql_class.h), The tests below work for pure binlogs or pure relay
    logs. Won't work for mixed relay logs but we don't create mixed
    relay logs (that is, there is no relay log with a format change
    except within the 3 first events, which mysqlbinlog handles
    gracefully). So this code should always be good.
  */

  if (likely(sql_mode_inited) &&
      (unlikely(print_event_info->sql_mode != sql_mode ||
                !print_event_info->sql_mode_inited)))
  {
    char llbuff[22];
    if (my_b_printf(file,"SET @@session.sql_mode=%s%s\n",
                    ullstr(sql_mode, llbuff), print_event_info->delimiter))
      goto err;
    print_event_info->sql_mode= sql_mode;
    print_event_info->sql_mode_inited= 1;
  }
  if (print_event_info->auto_increment_increment != auto_increment_increment ||
      print_event_info->auto_increment_offset != auto_increment_offset)
  {
    if (my_b_printf(file,"SET @@session.auto_increment_increment=%lu, @@session.auto_increment_offset=%lu%s\n",
                    auto_increment_increment,auto_increment_offset,
                    print_event_info->delimiter))
      goto err;
    print_event_info->auto_increment_increment= auto_increment_increment;
    print_event_info->auto_increment_offset=    auto_increment_offset;
  }

  /* TODO: print the catalog when we feature SET CATALOG */

  if (likely(charset_inited) &&
      (unlikely(!print_event_info->charset_inited ||
                memcmp(print_event_info->charset, charset, 6))))
  {
    CHARSET_INFO *cs_info= get_charset(uint2korr(charset), MYF(MY_WME));
    if (cs_info)
    {
      /* for mysql client */
      if (my_b_printf(file, "/*!\\C %s */%s\n",
1966
                      cs_info->cs_name.str, print_event_info->delimiter))
1967 1968 1969
        goto err;
    }
    if (my_b_printf(file,"SET "
1970
                    "@@session.character_set_client=%s,"
1971 1972 1973
                    "@@session.collation_connection=%d,"
                    "@@session.collation_server=%d"
                    "%s\n",
Marko Mäkelä's avatar
Marko Mäkelä committed
1974
                    cs_info->cs_name.str,
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
                    uint2korr(charset+2),
                    uint2korr(charset+4),
                    print_event_info->delimiter))
      goto err;
    memcpy(print_event_info->charset, charset, 6);
    print_event_info->charset_inited= 1;
  }
  if (time_zone_len)
  {
    if (memcmp(print_event_info->time_zone_str,
               time_zone_str, time_zone_len+1))
    {
      if (my_b_printf(file,"SET @@session.time_zone='%s'%s\n",
                      time_zone_str, print_event_info->delimiter))
        goto err;
      memcpy(print_event_info->time_zone_str, time_zone_str, time_zone_len+1);
    }
  }
  if (lc_time_names_number != print_event_info->lc_time_names_number)
  {
    if (my_b_printf(file, "SET @@session.lc_time_names=%d%s\n",
                    lc_time_names_number, print_event_info->delimiter))
      goto err;
    print_event_info->lc_time_names_number= lc_time_names_number;
  }
  if (charset_database_number != print_event_info->charset_database_number)
  {
    if (charset_database_number)
    {
      if (my_b_printf(file, "SET @@session.collation_database=%d%s\n",
                      charset_database_number, print_event_info->delimiter))
        goto err;
    }
    else if (my_b_printf(file, "SET @@session.collation_database=DEFAULT%s\n",
                         print_event_info->delimiter))
      goto err;
    print_event_info->charset_database_number= charset_database_number;
  }
  return 0;

err:
  return 1;
}


bool Query_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file, 0, this);

  /**
    reduce the size of io cache so that the write function is called
    for every call to my_b_write().
   */
  DBUG_EXECUTE_IF ("simulate_file_write_error",
                   {(&cache)->write_pos= (&cache)->write_end- 500;});
  if (print_query_header(&cache, print_event_info))
    goto err;
  if (!is_flashback)
  {
    if (my_b_write(&cache, (uchar*) query, q_len) ||
        my_b_printf(&cache, "\n%s\n", print_event_info->delimiter))
      goto err;
  }
  else // is_flashback == 1
  {
    if (strcmp("BEGIN", query) == 0)
    {
      if (my_b_write(&cache, (uchar*) "COMMIT", 6) ||
          my_b_printf(&cache, "\n%s\n", print_event_info->delimiter))
        goto err;
    }
    else if (strcmp("COMMIT", query) == 0)
    {
Marko Mäkelä's avatar
Marko Mäkelä committed
2048
      if (my_b_printf(&cache, "START TRANSACTION\n%s\n", print_event_info->delimiter))
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 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 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
        goto err;
    }
  }
  return cache.flush_data();
err:
  return 1;
}


bool Start_log_event_v3::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  DBUG_ENTER("Start_log_event_v3::print");

  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F);

  if (!print_event_info->short_form)
  {
    if (print_header(&cache, print_event_info, FALSE) ||
        my_b_printf(&cache, "\tStart: binlog v %d, server v %s created ",
                    binlog_version, server_version) ||
        print_timestamp(&cache))
      goto err;
    if (created)
      if (my_b_printf(&cache," at startup"))
        goto err;
    if (my_b_printf(&cache, "\n"))
      goto err;
    if (flags & LOG_EVENT_BINLOG_IN_USE_F)
      if (my_b_printf(&cache,
                      "# Warning: this binlog is either in use or was not "
                      "closed properly.\n"))
        goto err;
  }
  if (!is_artificial_event() && created)
  {
#ifdef WHEN_WE_HAVE_THE_RESET_CONNECTION_SQL_COMMAND
    /*
      This is for mysqlbinlog: like in replication, we want to delete the stale
      tmp files left by an unclean shutdown of mysqld (temporary tables)
      and rollback unfinished transaction.
      Probably this can be done with RESET CONNECTION (syntax to be defined).
    */
    if (my_b_printf(&cache,"RESET CONNECTION%s\n",
                    print_event_info->delimiter))
      goto err;
#else
    if (my_b_printf(&cache,"ROLLBACK%s\n", print_event_info->delimiter))
      goto err;
#endif
  }
  if (temp_buf &&
      print_event_info->base64_output_mode != BASE64_OUTPUT_NEVER &&
      !print_event_info->short_form)
  {
    /* BINLOG is matched with the delimiter below on the same level */
    bool do_print_encoded=
      print_event_info->base64_output_mode != BASE64_OUTPUT_DECODE_ROWS;
    if (do_print_encoded)
      my_b_printf(&cache, "BINLOG '\n");

    if (print_base64(&cache, print_event_info, do_print_encoded))
      goto err;

    if (do_print_encoded)
      my_b_printf(&cache, "'%s\n", print_event_info->delimiter);

    print_event_info->printed_fd_event= TRUE;
  }
  DBUG_RETURN(cache.flush_data());
err:
  DBUG_RETURN(1);
}


bool Start_encryption_log_event::print(FILE* file,
                                       PRINT_EVENT_INFO* print_event_info)
{
    Write_on_release_cache cache(&print_event_info->head_cache, file);
    StringBuffer<1024> buf;
    buf.append(STRING_WITH_LEN("# Encryption scheme: "));
    buf.append_ulonglong(crypto_scheme);
    buf.append(STRING_WITH_LEN(", key_version: "));
    buf.append_ulonglong(key_version);
    buf.append(STRING_WITH_LEN(", nonce: "));
    buf.append_hex(nonce, BINLOG_NONCE_LENGTH);
    buf.append(STRING_WITH_LEN("\n# The rest of the binlog is encrypted!\n"));
    if (my_b_write(&cache, (uchar*)buf.ptr(), buf.length()))
      return 1;
    return (cache.flush_data());
}


bool Load_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  return print(file, print_event_info, 0);
}


bool Load_log_event::print(FILE* file_arg, PRINT_EVENT_INFO* print_event_info,
			   bool commented)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file_arg);
  bool different_db= 1;
  DBUG_ENTER("Load_log_event::print");

  if (!print_event_info->short_form)
  {
    if (print_header(&cache, print_event_info, FALSE) ||
        my_b_printf(&cache, "\tQuery\tthread_id=%ld\texec_time=%ld\n",
                    thread_id, exec_time))
      goto err;
  }

  if (db)
  {
    /*
      If the database is different from the one of the previous statement, we
      need to print the "use" command, and we update the last_db.
      But if commented, the "use" is going to be commented so we should not
      update the last_db.
    */
    if ((different_db= memcmp(print_event_info->db, db, db_len + 1)) &&
        !commented)
      memcpy(print_event_info->db, db, db_len + 1);
  }

  if (db && db[0] && different_db)
    if (my_b_printf(&cache, "%suse %`s%s\n",
                    commented ? "# " : "",
                    db, print_event_info->delimiter))
      goto err;

  if (flags & LOG_EVENT_THREAD_SPECIFIC_F)
    if (my_b_printf(&cache,"%sSET @@session.pseudo_thread_id=%lu%s\n",
                    commented ? "# " : "", (ulong)thread_id,
                    print_event_info->delimiter))
      goto err;
  if (my_b_printf(&cache, "%sLOAD DATA ",
                  commented ? "# " : ""))
    goto err;
  if (check_fname_outside_temp_buf())
    if (my_b_write_string(&cache, "LOCAL "))
      goto err;
  if (my_b_printf(&cache, "INFILE '%-*s' ", fname_len, fname))
    goto err;

  if (sql_ex.opt_flags & REPLACE_FLAG)
  {
    if (my_b_write_string(&cache, "REPLACE "))
      goto err;
  }
  else if (sql_ex.opt_flags & IGNORE_FLAG)
    if (my_b_write_string(&cache, "IGNORE "))
      goto err;

  if (my_b_printf(&cache, "INTO TABLE `%s`", table_name) ||
      my_b_write_string(&cache, " FIELDS TERMINATED BY ") ||
      pretty_print_str(&cache, sql_ex.field_term, sql_ex.field_term_len))
    goto err;

  if (sql_ex.opt_flags & OPT_ENCLOSED_FLAG)
    if (my_b_write_string(&cache, " OPTIONALLY "))
      goto err;
  if (my_b_write_string(&cache, " ENCLOSED BY ") ||
      pretty_print_str(&cache, sql_ex.enclosed, sql_ex.enclosed_len) ||
      my_b_write_string(&cache, " ESCAPED BY ") ||
      pretty_print_str(&cache, sql_ex.escaped, sql_ex.escaped_len) ||
      my_b_write_string(&cache, " LINES TERMINATED BY ") ||
      pretty_print_str(&cache, sql_ex.line_term, sql_ex.line_term_len))
    goto err;

  if (sql_ex.line_start)
  {
    if (my_b_write_string(&cache," STARTING BY ") ||
        pretty_print_str(&cache, sql_ex.line_start, sql_ex.line_start_len))
      goto err;
  }
  if ((long) skip_lines > 0)
    if (my_b_printf(&cache, " IGNORE %ld LINES", (long) skip_lines))
      goto err;

  if (num_fields)
  {
    uint i;
    const char* field = fields;
    if (my_b_write_string(&cache, " ("))
      goto err;
    for (i = 0; i < num_fields; i++)
    {
      if (i)
        if (my_b_write_byte(&cache, ','))
          goto err;
      if (my_b_printf(&cache, "%`s", field))
        goto err;
      field += field_lens[i]  + 1;
    }
    if (my_b_write_byte(&cache, ')'))
      goto err;
  }

  if (my_b_printf(&cache, "%s\n", print_event_info->delimiter))
    goto err;
  DBUG_RETURN(cache.flush_data());
err:
  DBUG_RETURN(1);
}


bool Rotate_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  char buf[22];
  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F);
  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_write_string(&cache, "\tRotate to "))
    goto err;
  if (new_log_ident)
    if (my_b_write(&cache, (uchar*) new_log_ident, (uint)ident_len))
      goto err;
  if (my_b_printf(&cache, "  pos: %s\n", llstr(pos, buf)))
    goto err;
  return cache.flush_data();
err:
  return 1;
}


bool Binlog_checkpoint_log_event::print(FILE *file,
                                        PRINT_EVENT_INFO *print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F);

  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_write_string(&cache, "\tBinlog checkpoint ") ||
      my_b_write(&cache, (uchar*)binlog_file_name, binlog_file_len) ||
      my_b_write_byte(&cache, '\n'))
    return 1;
  return cache.flush_data();
}


bool
Gtid_list_log_event::print(FILE *file, PRINT_EVENT_INFO *print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F);
  char buf[21];
  uint32 i;

  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_printf(&cache, "\tGtid list ["))
    goto err;

  for (i= 0; i < count; ++i)
  {
    longlong10_to_str(list[i].seq_no, buf, 10);
    if (my_b_printf(&cache, "%u-%u-%s", list[i].domain_id,
                    list[i].server_id, buf))
      goto err;
    if (i < count-1)
      if (my_b_printf(&cache, ",\n# "))
        goto err;
  }
  if (my_b_printf(&cache, "]\n"))
    goto err;

  return cache.flush_data();
err:
  return 1;
}


bool Intvar_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  char llbuff[22];
  const char *UNINIT_VAR(msg);
  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F);

  if (!print_event_info->short_form)
  {
    if (print_header(&cache, print_event_info, FALSE) ||
        my_b_write_string(&cache, "\tIntvar\n"))
      goto err;
  }

  if (my_b_printf(&cache, "SET "))
    goto err;
  switch (type) {
  case LAST_INSERT_ID_EVENT:
    msg="LAST_INSERT_ID";
    break;
  case INSERT_ID_EVENT:
    msg="INSERT_ID";
    break;
  case INVALID_INT_EVENT:
  default: // cannot happen
    msg="INVALID_INT";
    break;
  }
  if (my_b_printf(&cache, "%s=%s%s\n",
                  msg, llstr(val,llbuff), print_event_info->delimiter))
    goto err;

  return cache.flush_data();
err:
  return 1;
}


bool Rand_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F);

  char llbuff[22],llbuff2[22];
  if (!print_event_info->short_form)
  {
    if (print_header(&cache, print_event_info, FALSE) ||
        my_b_write_string(&cache, "\tRand\n"))
      goto err;
  }
  if (my_b_printf(&cache, "SET @@RAND_SEED1=%s, @@RAND_SEED2=%s%s\n",
                  llstr(seed1, llbuff),llstr(seed2, llbuff2),
                  print_event_info->delimiter))
    goto err;

  return cache.flush_data();
err:
  return 1;
}


bool Xid_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F, this);

  if (!print_event_info->short_form)
  {
    char buf[64];
    longlong10_to_str(xid, buf, 10);

    if (print_header(&cache, print_event_info, FALSE) ||
        my_b_printf(&cache, "\tXid = %s\n", buf))
      goto err;
  }
Marko Mäkelä's avatar
Marko Mäkelä committed
2407
  if (my_b_printf(&cache, is_flashback ? "START TRANSACTION%s\n" : "COMMIT%s\n",
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
                  print_event_info->delimiter))
    goto err;

  return cache.flush_data();
err:
  return 1;
}


bool User_var_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F);

  if (!print_event_info->short_form)
  {
    if (print_header(&cache, print_event_info, FALSE) ||
        my_b_write_string(&cache, "\tUser_var\n"))
      goto err;
  }

  if (my_b_write_string(&cache, "SET @") ||
      my_b_write_backtick_quote(&cache, name, name_len))
    goto err;

  if (is_null)
  {
    if (my_b_printf(&cache, ":=NULL%s\n", print_event_info->delimiter))
      goto err;
  }
  else
  {
2440
    switch (m_type) {
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
    case REAL_RESULT:
      double real_val;
      char real_buf[FMT_G_BUFSIZE(14)];
      float8get(real_val, val);
      sprintf(real_buf, "%.14g", real_val);
      if (my_b_printf(&cache, ":=%s%s\n", real_buf,
                      print_event_info->delimiter))
        goto err;
      break;
    case INT_RESULT:
      char int_buf[22];
2452
      longlong10_to_str(uint8korr(val), int_buf,  is_unsigned() ? 10 : -10);
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
      if (my_b_printf(&cache, ":=%s%s\n", int_buf,
                      print_event_info->delimiter))
        goto err;
      break;
    case DECIMAL_RESULT:
    {
      char str_buf[200];
      int str_len= sizeof(str_buf) - 1;
      int precision= (int)val[0];
      int scale= (int)val[1];
      decimal_digit_t dec_buf[10];
      decimal_t dec;
      dec.len= 10;
      dec.buf= dec_buf;

      bin2decimal((uchar*) val+2, &dec, precision, scale);
      decimal2string(&dec, str_buf, &str_len, 0, 0, 0);
      str_buf[str_len]= 0;
      if (my_b_printf(&cache, ":=%s%s\n", str_buf,
                      print_event_info->delimiter))
        goto err;
      break;
    }
    case STRING_RESULT:
    {
      /*
        Let's express the string in hex. That's the most robust way. If we
        print it in character form instead, we need to escape it with
        character_set_client which we don't know (we will know it in 5.0, but
        in 4.1 we don't know it easily when we are printing
        User_var_log_event). Explanation why we would need to bother with
        character_set_client (quoting Bar):
        > Note, the parser doesn't switch to another unescaping mode after
        > it has met a character set introducer.
        > For example, if an SJIS client says something like:
        > SET @a= _ucs2 \0a\0b'
        > the string constant is still unescaped according to SJIS, not
        > according to UCS2.
      */
      char *hex_str;
      CHARSET_INFO *cs;
      bool error;

      // 2 hex digits / byte
2497
      hex_str= (char *) my_malloc(PSI_NOT_INSTRUMENTED, 2 * val_len + 1 + 3, MYF(MY_WME));
2498 2499 2500 2501 2502 2503 2504 2505 2506
      if (!hex_str)
        goto err;
      str_to_hex(hex_str, val, val_len);
      /*
        For proper behaviour when mysqlbinlog|mysql, we need to explicitly
        specify the variable's collation. It will however cause problems when
        people want to mysqlbinlog|mysql into another server not supporting the
        character set. But there's not much to do about this and it's unlikely.
      */
2507
      if (!(cs= get_charset(m_charset_number, MYF(0))))
2508 2509 2510 2511 2512 2513 2514 2515
      {        /*
          Generate an unusable command (=> syntax error) is probably the best
          thing we can do here.
        */
        error= my_b_printf(&cache, ":=???%s\n", print_event_info->delimiter);
      }
      else
        error= my_b_printf(&cache, ":=_%s %s COLLATE `%s`%s\n",
2516
                           cs->cs_name.str, hex_str, cs->coll_name.str,
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
                           print_event_info->delimiter);
      my_free(hex_str);
      if (unlikely(error))
        goto err;
      break;
    }
    case ROW_RESULT:
    default:
      DBUG_ASSERT(0);
      break;
    }
  }

  return cache.flush_data();
err:
  return 1;
}


#ifdef HAVE_REPLICATION

bool Unknown_log_event::print(FILE* file_arg, PRINT_EVENT_INFO* print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file_arg);

  if (what != ENCRYPTED)
  {
    if (print_header(&cache, print_event_info, FALSE) ||
        my_b_printf(&cache, "\n# Unknown event\n"))
      goto err;
  }
  else if (my_b_printf(&cache, "# Encrypted event\n"))
    goto err;

  return cache.flush_data();
err:
  return 1;
}


bool Stop_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F, this);

  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_write_string(&cache, "\tStop\n"))
    return 1;
  return cache.flush_data();
}

#endif


bool Create_file_log_event::print(FILE* file,
                                  PRINT_EVENT_INFO* print_event_info,
				  bool enable_local)
{
  if (print_event_info->short_form)
  {
    if (enable_local && check_fname_outside_temp_buf())
      return Load_log_event::print(file, print_event_info);
    return 0;
  }

  Write_on_release_cache cache(&print_event_info->head_cache, file);

  if (enable_local)
  {
    if (Load_log_event::print(file, print_event_info,
                              !check_fname_outside_temp_buf()))
      goto err;

    /**
      reduce the size of io cache so that the write function is called
      for every call to my_b_printf().
     */
    DBUG_EXECUTE_IF ("simulate_create_event_write_error",
                     {(&cache)->write_pos= (&cache)->write_end;
                     DBUG_SET("+d,simulate_file_write_error");});
    /*
      That one is for "file_id: etc" below: in mysqlbinlog we want the #, in
      SHOW BINLOG EVENTS we don't.
     */
    if (my_b_write_byte(&cache, '#'))
      goto err;
  }

  if (my_b_printf(&cache, " file_id: %d  block_len: %d\n", file_id, block_len))
    goto err;

  return cache.flush_data();
err:
  return 1;

}


bool Create_file_log_event::print(FILE* file,
                                  PRINT_EVENT_INFO* print_event_info)
{
  return print(file, print_event_info, 0);
}


/*
  Append_block_log_event::print()
*/

bool Append_block_log_event::print(FILE* file,
				   PRINT_EVENT_INFO* print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file);

  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_printf(&cache, "\n#%s: file_id: %d  block_len: %d\n",
                  get_type_str(), file_id, block_len))
    goto err;

  return cache.flush_data();
err:
  return 1;
}


/*
  Delete_file_log_event::print()
*/

bool Delete_file_log_event::print(FILE* file,
				  PRINT_EVENT_INFO* print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file);

  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_printf(&cache, "\n#Delete_file: file_id=%u\n", file_id))
    return 1;

  return cache.flush_data();
}

/*
  Execute_load_log_event::print()
*/

bool Execute_load_log_event::print(FILE* file,
				   PRINT_EVENT_INFO* print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file);

  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_printf(&cache, "\n#Exec_load: file_id=%d\n",
                  file_id))
    return 1;

  return cache.flush_data();
}

bool Execute_load_query_log_event::print(FILE* file,
                                         PRINT_EVENT_INFO* print_event_info)
{
  return print(file, print_event_info, 0);
}

/**
  Prints the query as LOAD DATA LOCAL and with rewritten filename.
*/
bool Execute_load_query_log_event::print(FILE* file,
                                         PRINT_EVENT_INFO* print_event_info,
                                         const char *local_fname)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file);

  if (print_query_header(&cache, print_event_info))
    goto err;

  /**
    reduce the size of io cache so that the write function is called
    for every call to my_b_printf().
   */
  DBUG_EXECUTE_IF ("simulate_execute_event_write_error",
                   {(&cache)->write_pos= (&cache)->write_end;
                   DBUG_SET("+d,simulate_file_write_error");});

  if (local_fname)
  {
    if (my_b_write(&cache, (uchar*) query, fn_pos_start) ||
        my_b_write_string(&cache, " LOCAL INFILE ") ||
        pretty_print_str(&cache, local_fname, (int)strlen(local_fname)))
      goto err;

    if (dup_handling == LOAD_DUP_REPLACE)
      if (my_b_write_string(&cache, " REPLACE"))
        goto err;

    if (my_b_write_string(&cache, " INTO") ||
        my_b_write(&cache, (uchar*) query + fn_pos_end, q_len-fn_pos_end) ||
        my_b_printf(&cache, "\n%s\n", print_event_info->delimiter))
      goto err;
  }
  else
  {
    if (my_b_write(&cache, (uchar*) query, q_len) ||
        my_b_printf(&cache, "\n%s\n", print_event_info->delimiter))
      goto err;
  }

  if (!print_event_info->short_form)
    my_b_printf(&cache, "# file_id: %d \n", file_id);

  return cache.flush_data();
err:
  return 1;
}



const char str_binlog[]= "\nBINLOG '\n";
const char fmt_delim[]=   "'%s\n";
const char fmt_n_delim[]= "\n'%s";
const char fmt_frag[]= "\nSET @binlog_fragment_%d ='\n";
const char fmt_binlog2[]= "BINLOG @binlog_fragment_0, @binlog_fragment_1%s\n";

/**
  Print an event "body" cache to @c file possibly in two fragments.
  Each fragement is optionally per @c do_wrap to produce an SQL statement.

  @param file      a file to print to
  @param body      the "body" IO_CACHE of event
  @param do_wrap   whether to wrap base64-encoded strings with
                   SQL cover.
  @param delimiter delimiter string

  @param is_verbose  MDEV-10362 workraround parameter to pass
                   info on presence of verbose printout in cache encoded data

  The function signals on any error through setting @c body->error to -1.
*/
bool copy_cache_to_file_wrapped(IO_CACHE *body,
                                FILE *file,
                                bool do_wrap,
                                const char *delimiter,
Marko Mäkelä's avatar
Marko Mäkelä committed
2774
                                bool is_verbose /*TODO: remove */)
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806
{
  const my_off_t cache_size= my_b_tell(body);

  if (reinit_io_cache(body, READ_CACHE, 0L, FALSE, FALSE))
    goto err;

  if (!do_wrap)
  {
    my_b_copy_to_file(body, file, SIZE_T_MAX);
  }
  else if (4 + sizeof(str_binlog) + cache_size + sizeof(fmt_delim) >
           opt_binlog_rows_event_max_encoded_size)
  {
    /*
      2 fragments can always represent near 1GB row-based
      base64-encoded event as two strings each of size less than
      max(max_allowed_packet). Greater number of fragments does not
      save from potential need to tweak (increase) @@max_allowed_packet
      before to process the fragments. So 2 is safe and enough.

      Split the big query when its packet size's estimation exceeds a
      limit. The estimate includes the maximum packet header
      contribution of non-compressed packet.
    */
    my_fprintf(file, fmt_frag, 0);
    if (my_b_copy_to_file(body, file, (size_t) cache_size/2 + 1))
      goto err;
    my_fprintf(file, fmt_n_delim, delimiter);

    my_fprintf(file, fmt_frag, 1);
    if (my_b_copy_to_file(body, file, SIZE_T_MAX))
      goto err;
Marko Mäkelä's avatar
Marko Mäkelä committed
2807
    my_fprintf(file, fmt_delim, delimiter);
2808 2809 2810 2811 2812 2813 2814 2815

    my_fprintf(file, fmt_binlog2, delimiter);
  }
  else
  {
    my_fprintf(file, str_binlog);
    if (my_b_copy_to_file(body, file, SIZE_T_MAX))
      goto err;
Marko Mäkelä's avatar
Marko Mäkelä committed
2816
    my_fprintf(file, fmt_delim, delimiter);
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
  }
  reinit_io_cache(body, WRITE_CACHE, 0, FALSE, TRUE);

  return false;

err:
  body->error = -1;
  return true;
}


/**
  Print an event "body" cache to @c file possibly in two fragments.
  Each fragement is optionally per @c do_wrap to produce an SQL statement.

  @param file      a file to print to
  @param body      the "body" IO_CACHE of event
  @param do_wrap   whether to wrap base64-encoded strings with
                   SQL cover.
  @param delimiter delimiter string

  The function signals on any error through setting @c body->error to -1.
*/
bool copy_cache_to_string_wrapped(IO_CACHE *cache,
                                  LEX_STRING *to,
                                  bool do_wrap,
                                  const char *delimiter,
                                  bool is_verbose)
{
  const my_off_t cache_size= my_b_tell(cache);
  // contribution to total size estimate of formating
  const size_t fmt_size=
    sizeof(str_binlog) + 2*(sizeof(fmt_frag) + 2 /* %d */) +
    sizeof(fmt_delim)  + sizeof(fmt_n_delim)               +
    sizeof(fmt_binlog2) +
    3*PRINT_EVENT_INFO::max_delimiter_size;

  if (reinit_io_cache(cache, READ_CACHE, 0L, FALSE, FALSE))
    goto err;

2857
  if (!(to->str= (char*) my_malloc(PSI_NOT_INSTRUMENTED, (size_t)cache->end_of_file + fmt_size,
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
                                   MYF(0))))
  {
    perror("Out of memory: can't allocate memory in "
           "copy_cache_to_string_wrapped().");
    goto err;
  }

  if (!do_wrap)
  {
    if (my_b_read(cache, (uchar*) to->str,
                  (to->length= (size_t)cache->end_of_file)))
      goto err;
  }
  else if (4 + sizeof(str_binlog) + cache_size + sizeof(fmt_delim) >
           opt_binlog_rows_event_max_encoded_size)
  {
    /*
      2 fragments can always represent near 1GB row-based
      base64-encoded event as two strings each of size less than
      max(max_allowed_packet). Greater number of fragments does not
      save from potential need to tweak (increase) @@max_allowed_packet
      before to process the fragments. So 2 is safe and enough.

      Split the big query when its packet size's estimation exceeds a
      limit. The estimate includes the maximum packet header
      contribution of non-compressed packet.
    */
    char *str= to->str;
    size_t add_to_len;

    str += (to->length= sprintf(str, fmt_frag, 0));
    if (my_b_read(cache, (uchar*) str, (uint32) (cache_size/2 + 1)))
      goto err;
    str += (add_to_len = (uint32) (cache_size/2 + 1));
    to->length += add_to_len;
    str += (add_to_len= sprintf(str, fmt_n_delim, delimiter));
    to->length += add_to_len;

    str += (add_to_len= sprintf(str, fmt_frag, 1));
    to->length += add_to_len;
    if (my_b_read(cache, (uchar*) str, uint32(cache->end_of_file - (cache_size/2 + 1))))
      goto err;
    str += (add_to_len= uint32(cache->end_of_file - (cache_size/2 + 1)));
    to->length += add_to_len;
    {
      str += (add_to_len= sprintf(str , fmt_delim, delimiter));
      to->length += add_to_len;
    }
    to->length += sprintf(str, fmt_binlog2, delimiter);
  }
  else
  {
    char *str= to->str;

    str += (to->length= sprintf(str, str_binlog));
    if (my_b_read(cache, (uchar*) str, (size_t)cache->end_of_file))
      goto err;
    str += cache->end_of_file;
    to->length += (size_t)cache->end_of_file;
      to->length += sprintf(str , fmt_delim, delimiter);
  }

  reinit_io_cache(cache, WRITE_CACHE, 0, FALSE, TRUE);

  return false;

err:
  cache->error= -1;
  return true;
}

/**
  The function invokes base64 encoder to run on the current
  event string and store the result into two caches.
  When the event ends the current statement the caches are is copied into
  the argument file.
  Copying is also concerned how to wrap the event, specifically to produce
  a valid SQL syntax.
  When the encoded data size is within max(MAX_ALLOWED_PACKET)
  a regular BINLOG query is composed. Otherwise it is build as fragmented

    SET @binlog_fragment_0='...';
    SET @binlog_fragment_1='...';
    BINLOG @binlog_fragment_0, @binlog_fragment_1;

  where fragments are represented by a pair of indexed user
  "one shot" variables.

  @note
  If any changes made don't forget to duplicate them to
  Old_rows_log_event as long as it's supported.

  @param file               pointer to IO_CACHE
  @param print_event_info   pointer to print_event_info specializing
                            what out of and how to print the event
  @param name               the name of a table that the event operates on

  The function signals on any error of cache access through setting
  that cache's @c error to -1.
*/
bool Rows_log_event::print_helper(FILE *file,
                                  PRINT_EVENT_INFO *print_event_info,
                                  char const *const name)
{
  IO_CACHE *const head= &print_event_info->head_cache;
  IO_CACHE *const body= &print_event_info->body_cache;
Marko Mäkelä's avatar
Marko Mäkelä committed
2964
  IO_CACHE *const tail= &print_event_info->tail_cache;
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
#ifdef WHEN_FLASHBACK_REVIEW_READY
  IO_CACHE *const sql= &print_event_info->review_sql_cache;
#endif
  bool do_print_encoded=
    print_event_info->base64_output_mode != BASE64_OUTPUT_NEVER &&
    print_event_info->base64_output_mode != BASE64_OUTPUT_DECODE_ROWS &&
    !print_event_info->short_form;
  bool const last_stmt_event= get_flags(STMT_END_F);

  if (!print_event_info->short_form)
  {
    char llbuff[22];

    print_header(head, print_event_info, !last_stmt_event);
    if (my_b_printf(head, "\t%s: table id %s%s\n",
                    name, ullstr(m_table_id, llbuff),
                    last_stmt_event ? " flags: STMT_END_F" : ""))
      goto err;
  }
  if (!print_event_info->short_form || print_event_info->print_row_count)
    if (print_base64(body, print_event_info, do_print_encoded))
      goto err;

  if (last_stmt_event)
  {
    if (!is_flashback)
    {
      if (copy_event_cache_to_file_and_reinit(head, file) ||
          copy_cache_to_file_wrapped(body, file, do_print_encoded,
                                     print_event_info->delimiter,
Marko Mäkelä's avatar
Marko Mäkelä committed
2995 2996
                                     print_event_info->verbose) ||
          copy_event_cache_to_file_and_reinit(tail, file))
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
        goto err;
    }
    else
    {
    LEX_STRING tmp_str;

    if (copy_event_cache_to_string_and_reinit(head, &tmp_str))
      return 1;
    output_buf.append(tmp_str.str, tmp_str.length);  // Not \0 terminated);
    my_free(tmp_str.str);

    if (copy_cache_to_string_wrapped(body, &tmp_str, do_print_encoded,
                                     print_event_info->delimiter,
                                     print_event_info->verbose))
      return 1;
    output_buf.append(tmp_str.str, tmp_str.length);
    my_free(tmp_str.str);
Marko Mäkelä's avatar
Marko Mäkelä committed
3014 3015 3016 3017 3018
    if (copy_event_cache_to_string_and_reinit(tail, &tmp_str))
      return 1;
    output_buf.append(tmp_str.str, tmp_str.length);
    my_free(tmp_str.str);

3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
#ifdef WHEN_FLASHBACK_REVIEW_READY
    if (copy_event_cache_to_string_and_reinit(sql, &tmp_str))
      return 1;
    output_buf.append(tmp_str.str, tmp_str.length);
    my_free(tmp_str.str);
#endif
    }
  }

  return 0;
err:
  return 1;
}


bool Annotate_rows_log_event::print(FILE *file, PRINT_EVENT_INFO *pinfo)
{
  char *pbeg;   // beginning of the next line
  char *pend;   // end of the next line
  uint cnt= 0;  // characters counter

  if (!pinfo->short_form)
  {
    if (print_header(&pinfo->head_cache, pinfo, TRUE) ||
        my_b_printf(&pinfo->head_cache, "\tAnnotate_rows:\n"))
      goto err;
  }
  else if (my_b_printf(&pinfo->head_cache, "# Annotate_rows:\n"))
    goto err;

  for (pbeg= m_query_txt; ; pbeg= pend)
  {
    // skip all \r's and \n's at the beginning of the next line
    for (;; pbeg++)
    {
      if (++cnt > m_query_len)
        return 0;

      if (*pbeg != '\r' && *pbeg != '\n')
        break;
    }

    // find end of the next line
    for (pend= pbeg + 1;
         ++cnt <= m_query_len && *pend != '\r' && *pend != '\n';
         pend++)
      ;

    // print next line
    if (my_b_write(&pinfo->head_cache, (const uchar*) "#Q> ", 4) ||
        my_b_write(&pinfo->head_cache, (const uchar*) pbeg, pend - pbeg) ||
        my_b_write(&pinfo->head_cache, (const uchar*) "\n", 1))
      goto err;
  }

  return 0;
err:
  return 1;
}


/*
  Rewrite database name for the event to name specified by new_db
  SYNOPSIS
    new_db   Database name to change to
    new_len  Length
    desc     Event describing binlog that we're writing to.

  DESCRIPTION
    Reset db name. This function assumes that temp_buf member contains event
    representation taken from a binary log. It resets m_dbnam and m_dblen and
    rewrites temp_buf with new db name.

  RETURN 
    0     - Success
    other - Error
*/

int Table_map_log_event::rewrite_db(const char* new_db, size_t new_len,
                                    const Format_description_log_event* desc)
{
  DBUG_ENTER("Table_map_log_event::rewrite_db");
  DBUG_ASSERT(temp_buf);

  uint header_len= MY_MIN(desc->common_header_len,
                       LOG_EVENT_MINIMAL_HEADER_LEN) + TABLE_MAP_HEADER_LEN;
  int len_diff;

  if (!(len_diff= (int)(new_len - m_dblen)))
  {
    memcpy((void*) (temp_buf + header_len + 1), new_db, m_dblen + 1);
    memcpy((void*) m_dbnam, new_db, m_dblen + 1);
    DBUG_RETURN(0);
  }

  // Create new temp_buf
  ulong event_cur_len= uint4korr(temp_buf + EVENT_LEN_OFFSET);
  ulong event_new_len= event_cur_len + len_diff;
3117 3118
  uchar* new_temp_buf= (uchar*) my_malloc(PSI_NOT_INSTRUMENTED, event_new_len,
                                          MYF(MY_WME));
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128

  if (!new_temp_buf)
  {
    sql_print_error("Table_map_log_event::rewrite_db: "
                    "failed to allocate new temp_buf (%d bytes required)",
                    event_new_len);
    DBUG_RETURN(-1);
  }

  // Rewrite temp_buf
3129
  uchar *ptr= new_temp_buf;
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
  size_t cnt= 0;

  // Copy header and change event length
  memcpy(ptr, temp_buf, header_len);
  int4store(ptr + EVENT_LEN_OFFSET, event_new_len);
  ptr += header_len;
  cnt += header_len;

  // Write new db name length and new name
  DBUG_ASSERT(new_len < 0xff);
  *ptr++ = (char)new_len;
  memcpy(ptr, new_db, new_len + 1);
  ptr += new_len + 1;
  cnt += m_dblen + 2;

  // Copy rest part
  memcpy(ptr, temp_buf + cnt, event_cur_len - cnt);

  // Reregister temp buf
  free_temp_buf();
  register_temp_buf(new_temp_buf, TRUE);

  // Reset m_dbnam and m_dblen members
  m_dblen= new_len;

  // m_dbnam resides in m_memory together with m_tblnam and m_coltype
  uchar* memory= m_memory;
  char const* tblnam= m_tblnam;
  uchar* coltype= m_coltype;

3160
  m_memory= (uchar*) my_multi_malloc(PSI_NOT_INSTRUMENTED, MYF(MY_WME),
3161 3162 3163 3164 3165 3166 3167 3168 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
                                     &m_dbnam, (uint) m_dblen + 1,
                                     &m_tblnam, (uint) m_tbllen + 1,
                                     &m_coltype, (uint) m_colcnt,
                                     NullS);

  if (!m_memory)
  {
    sql_print_error("Table_map_log_event::rewrite_db: "
                    "failed to allocate new m_memory (%d + %d + %d bytes required)",
                    m_dblen + 1, m_tbllen + 1, m_colcnt);
    DBUG_RETURN(-1);
  }

  memcpy((void*)m_dbnam, new_db, m_dblen + 1);
  memcpy((void*)m_tblnam, tblnam, m_tbllen + 1);
  memcpy(m_coltype, coltype, m_colcnt);

  my_free(memory);
  DBUG_RETURN(0);
}


bool Table_map_log_event::print(FILE *file, PRINT_EVENT_INFO *print_event_info)
{
  if (!print_event_info->short_form)
  {
    char llbuff[22];

    print_header(&print_event_info->head_cache, print_event_info, TRUE);
    if (my_b_printf(&print_event_info->head_cache,
                    "\tTable_map: %`s.%`s mapped to number %s%s\n",
                    m_dbnam, m_tblnam, ullstr(m_table_id, llbuff),
                    ((m_flags & TM_BIT_HAS_TRIGGERS_F) ?
                     " (has triggers)" : "")))
      goto err;
  }
  if (!print_event_info->short_form || print_event_info->print_row_count)
  {
3199 3200 3201 3202 3203 3204 3205 3206 3207

    if (print_event_info->print_table_metadata)
    {
      Optional_metadata_fields fields(m_optional_metadata,
                                      m_optional_metadata_len);

      print_columns(&print_event_info->head_cache, fields);
      print_primary_key(&print_event_info->head_cache, fields);
    }
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
    bool do_print_encoded=
      print_event_info->base64_output_mode != BASE64_OUTPUT_NEVER &&
      print_event_info->base64_output_mode != BASE64_OUTPUT_DECODE_ROWS &&
      !print_event_info->short_form;

    if (print_base64(&print_event_info->body_cache, print_event_info,
                     do_print_encoded) ||
        copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
                                            file))
      goto err;
  }

  return 0;
err:
  return 1;
}

3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
/**
  Interface for iterator over charset columns.
*/
class Table_map_log_event::Charset_iterator
{
 public:
  typedef Table_map_log_event::Optional_metadata_fields::Default_charset
      Default_charset;
  virtual const CHARSET_INFO *next()= 0;
  virtual ~Charset_iterator(){};
  /**
    Factory method to create an instance of the appropriate subclass.
  */
  static std::unique_ptr<Charset_iterator> create_charset_iterator(
      const Default_charset &default_charset,
      const std::vector<uint> &column_charset);
};

/**
  Implementation of charset iterator for the DEFAULT_CHARSET type.
*/
class Table_map_log_event::Default_charset_iterator : public Charset_iterator
{
 public:
  Default_charset_iterator(const Default_charset &default_charset)
      : m_iterator(default_charset.charset_pairs.begin()),
        m_end(default_charset.charset_pairs.end()),
        m_column_index(0),
        m_default_charset_info(
            get_charset(default_charset.default_charset, 0)) {}

  const CHARSET_INFO *next() override {
    const CHARSET_INFO *ret;
    if (m_iterator != m_end && m_iterator->first == m_column_index) {
      ret = get_charset(m_iterator->second, 0);
      m_iterator++;
    } else
      ret = m_default_charset_info;
    m_column_index++;
    return ret;
  }
  ~Default_charset_iterator(){};

 private:
  std::vector<Optional_metadata_fields::uint_pair>::const_iterator m_iterator,
      m_end;
  uint m_column_index;
  const CHARSET_INFO *m_default_charset_info;
};
//Table_map_log_event::Default_charset_iterator::~Default_charset_iterator(){int a=8;a++; a--;};
/**
  Implementation of charset iterator for the COLUMNT_CHARSET type.
*/
class Table_map_log_event::Column_charset_iterator : public Charset_iterator
{
 public:
  Column_charset_iterator(const std::vector<uint> &column_charset)
      : m_iterator(column_charset.begin()), m_end(column_charset.end()) {}

  const CHARSET_INFO *next() override {
    const CHARSET_INFO *ret = nullptr;
    if (m_iterator != m_end) {
      ret = get_charset(*m_iterator, 0);
      m_iterator++;
    }
    return ret;
  }

 ~Column_charset_iterator(){};
 private:
  std::vector<uint>::const_iterator m_iterator;
  std::vector<uint>::const_iterator m_end;
};
//Table_map_log_event::Column_charset_iterator::~Column_charset_iterator(){int a=8;a++; a--;};

std::unique_ptr<Table_map_log_event::Charset_iterator>
Table_map_log_event::Charset_iterator::create_charset_iterator(
    const Default_charset &default_charset,
    const std::vector<uint> &column_charset)
{
  if (!default_charset.empty())
    return std::unique_ptr<Charset_iterator>(
        new Default_charset_iterator(default_charset));
  else
    return std::unique_ptr<Charset_iterator>(
        new Column_charset_iterator(column_charset));
}
/**
   return the string name of a type.

   @param[in] type  type of a column
   @param[in|out] meta_ptr  the meta_ptr of the column. If the type doesn't have
                            metadata, it will not change  meta_ptr, otherwise
                            meta_ptr will be moved to the end of the column's
                            metadat.
   @param[in] cs charset of the column if it is a character column.
   @param[out] typestr  buffer to storing the string name of the type
   @param[in] typestr_length  length of typestr
   @param[in] geometry_type  internal geometry_type
 */
static void get_type_name(uint type, unsigned char** meta_ptr,
                          const CHARSET_INFO *cs, char *typestr,
                          uint typestr_length, unsigned int geometry_type)
{
  switch (type) {
  case MYSQL_TYPE_LONG:
    my_snprintf(typestr, typestr_length, "%s", "INT");
    break;
  case MYSQL_TYPE_TINY:
    my_snprintf(typestr, typestr_length, "TINYINT");
    break;
  case MYSQL_TYPE_SHORT:
    my_snprintf(typestr, typestr_length, "SMALLINT");
    break;
  case MYSQL_TYPE_INT24:
    my_snprintf(typestr, typestr_length, "MEDIUMINT");
    break;
  case MYSQL_TYPE_LONGLONG:
    my_snprintf(typestr, typestr_length, "BIGINT");
    break;
  case MYSQL_TYPE_NEWDECIMAL:
      my_snprintf(typestr, typestr_length, "DECIMAL(%d,%d)",
                  (*meta_ptr)[0], (*meta_ptr)[1]);
      (*meta_ptr)+= 2;
      break;
  case MYSQL_TYPE_FLOAT:
    my_snprintf(typestr, typestr_length, "FLOAT");
    (*meta_ptr)++;
    break;
  case MYSQL_TYPE_DOUBLE:
    my_snprintf(typestr, typestr_length, "DOUBLE");
    (*meta_ptr)++;
    break;
  case MYSQL_TYPE_BIT:
    my_snprintf(typestr, typestr_length, "BIT(%d)",
                (((*meta_ptr)[0])) + (*meta_ptr)[1]*8);
    (*meta_ptr)+= 2;
    break;
  case MYSQL_TYPE_TIMESTAMP2:
    if (**meta_ptr != 0)
      my_snprintf(typestr, typestr_length, "TIMESTAMP(%d)", **meta_ptr);
    else
      my_snprintf(typestr, typestr_length, "TIMESTAMP");
    (*meta_ptr)++;
    break;
  case MYSQL_TYPE_DATETIME2:
    if (**meta_ptr != 0)
      my_snprintf(typestr, typestr_length, "DATETIME(%d)", **meta_ptr);
    else
      my_snprintf(typestr, typestr_length, "DATETIME");
    (*meta_ptr)++;
    break;
  case MYSQL_TYPE_TIME2:
    if (**meta_ptr != 0)
      my_snprintf(typestr, typestr_length, "TIME(%d)", **meta_ptr);
    else
      my_snprintf(typestr, typestr_length, "TIME");
    (*meta_ptr)++;
    break;
  case MYSQL_TYPE_NEWDATE:
  case MYSQL_TYPE_DATE:
    my_snprintf(typestr, typestr_length, "DATE");
    break;
  case MYSQL_TYPE_YEAR:
    my_snprintf(typestr, typestr_length, "YEAR");
    break;
  case MYSQL_TYPE_ENUM:
    my_snprintf(typestr, typestr_length, "ENUM");
    (*meta_ptr)+= 2;
    break;
  case MYSQL_TYPE_SET:
    my_snprintf(typestr, typestr_length, "SET");
    (*meta_ptr)+= 2;
    break;
  case MYSQL_TYPE_BLOB:
    {
      bool is_text= (cs && cs->number != my_charset_bin.number);
      const char *names[5][2] = {
        {"INVALID_BLOB(%d)", "INVALID_TEXT(%d)"},
        {"TINYBLOB", "TINYTEXT"},
        {"BLOB", "TEXT"},
        {"MEDIUMBLOB", "MEDIUMTEXT"},
        {"LONGBLOB", "LONGTEXT"}
      };
      unsigned char size= **meta_ptr;

      if (size == 0 || size > 4)
        my_snprintf(typestr, typestr_length, names[0][is_text], size);
      else
        my_snprintf(typestr, typestr_length, names[**meta_ptr][is_text]);

      (*meta_ptr)++;
    }
    break;
  case MYSQL_TYPE_VARCHAR:
  case MYSQL_TYPE_VAR_STRING:
    if (cs && cs->number != my_charset_bin.number)
      my_snprintf(typestr, typestr_length, "VARCHAR(%d)",
                  uint2korr(*meta_ptr)/cs->mbmaxlen);
    else
      my_snprintf(typestr, typestr_length, "VARBINARY(%d)",
                  uint2korr(*meta_ptr));

    (*meta_ptr)+= 2;
    break;
  case MYSQL_TYPE_STRING:
    {
      uint byte0= (*meta_ptr)[0];
      uint byte1= (*meta_ptr)[1];
      uint len= (((byte0 & 0x30) ^ 0x30) << 4) | byte1;

      if (cs && cs->number != my_charset_bin.number)
        my_snprintf(typestr, typestr_length, "CHAR(%d)", len/cs->mbmaxlen);
      else
        my_snprintf(typestr, typestr_length, "BINARY(%d)", len);

      (*meta_ptr)+= 2;
    }
    break;
  case MYSQL_TYPE_GEOMETRY:
    {
      const char* names[8] = {
        "GEOMETRY", "POINT", "LINESTRING", "POLYGON", "MULTIPOINT",
        "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION"
      };
      if (geometry_type < 8)
        my_snprintf(typestr, typestr_length, names[geometry_type]);
      else
        my_snprintf(typestr, typestr_length, "INVALID_GEOMETRY_TYPE(%u)",
                    geometry_type);
      (*meta_ptr)++;
    }
    break;
  default:
    *typestr= 0;
    break;
  }
}

void Table_map_log_event::print_columns(IO_CACHE *file,
                                        const Optional_metadata_fields &fields)
{
  unsigned char* field_metadata_ptr= m_field_metadata;
  std::vector<bool>::const_iterator signedness_it= fields.m_signedness.begin();

  std::unique_ptr<Charset_iterator> charset_it =
      Charset_iterator::create_charset_iterator(fields.m_default_charset,
                                                fields.m_column_charset);
  std::unique_ptr<Charset_iterator> enum_and_set_charset_it =
      Charset_iterator::create_charset_iterator(
          fields.m_enum_and_set_default_charset,
          fields.m_enum_and_set_column_charset);
  std::vector<std::string>::const_iterator col_names_it=
    fields.m_column_name.begin();
  std::vector<Optional_metadata_fields::str_vector>::const_iterator
    set_str_values_it= fields.m_set_str_value.begin();
  std::vector<Optional_metadata_fields::str_vector>::const_iterator
    enum_str_values_it= fields.m_enum_str_value.begin();
  std::vector<unsigned int>::const_iterator geometry_type_it=
    fields.m_geometry_type.begin();

  uint geometry_type= 0;

  my_b_printf(file, "# Columns(");

  for (unsigned long i= 0; i < m_colcnt; i++)
  {
    uint real_type = m_coltype[i];
    if (real_type == MYSQL_TYPE_STRING &&
        (*field_metadata_ptr == MYSQL_TYPE_ENUM ||
         *field_metadata_ptr == MYSQL_TYPE_SET))
      real_type= *field_metadata_ptr;

    // Get current column's collation id if it is a character, enum,
    // or set column
    const CHARSET_INFO *cs = NULL;
    if (is_character_type(real_type))
      cs = charset_it->next();
    else if (is_enum_or_set_type(real_type))
      cs = enum_and_set_charset_it->next();

    // Print column name
    if (col_names_it != fields.m_column_name.end())
    {
      pretty_print_identifier(file, col_names_it->c_str(), col_names_it->size());
      my_b_printf(file, " ");
      col_names_it++;
    }


    // update geometry_type for geometry columns
    if (real_type == MYSQL_TYPE_GEOMETRY)
    {
      geometry_type= (geometry_type_it != fields.m_geometry_type.end()) ?
        *geometry_type_it++ : 0;
    }

    // print column type
    const uint TYPE_NAME_LEN = 100;
    char type_name[TYPE_NAME_LEN];
    get_type_name(real_type, &field_metadata_ptr, cs, type_name,
                  TYPE_NAME_LEN, geometry_type);

    if (type_name[0] == '\0')
    {
      my_b_printf(file, "INVALID_TYPE(%d)", real_type);
      continue;
    }
    my_b_printf(file, "%s", type_name);

    // Print UNSIGNED for numeric column
    if (is_numeric_type(real_type) &&
        signedness_it != fields.m_signedness.end())
    {
      if (*signedness_it == true)
        my_b_printf(file, " UNSIGNED");
      signedness_it++;
    }

    // if the column is not marked as 'null', print 'not null'
    if (!(m_null_bits[(i / 8)] & (1 << (i % 8))))
      my_b_printf(file, " NOT NULL");

    // Print string values of SET and ENUM column
    const Optional_metadata_fields::str_vector *str_values= NULL;
    if (real_type == MYSQL_TYPE_ENUM &&
        enum_str_values_it != fields.m_enum_str_value.end())
    {
      str_values= &(*enum_str_values_it);
      enum_str_values_it++;
    }
    else if (real_type == MYSQL_TYPE_SET &&
             set_str_values_it != fields.m_set_str_value.end())
    {
      str_values= &(*set_str_values_it);
      set_str_values_it++;
    }

    if (str_values != NULL)
    {
      const char *separator= "(";
      for (Optional_metadata_fields::str_vector::const_iterator it=
             str_values->begin(); it != str_values->end(); it++)
      {
        my_b_printf(file, "%s", separator);
        pretty_print_str(file, it->c_str(), it->size());
        separator= ",";
      }
      my_b_printf(file, ")");
    }
    // Print column character set, except in text columns with binary collation
    if (cs != NULL &&
        (is_enum_or_set_type(real_type) || cs->number != my_charset_bin.number))
3578 3579
      my_b_printf(file, " CHARSET %s COLLATE %s", cs->cs_name.str,
                  cs->coll_name.str);
3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
    if (i != m_colcnt - 1) my_b_printf(file, ",\n#         ");
  }
  my_b_printf(file, ")");
  my_b_printf(file, "\n");
}

void Table_map_log_event::print_primary_key
  (IO_CACHE *file,const Optional_metadata_fields &fields)
{
  if (!fields.m_primary_key.empty())
  {
    my_b_printf(file, "# Primary Key(");

    std::vector<Optional_metadata_fields::uint_pair>::const_iterator it=
      fields.m_primary_key.begin();

    for (; it != fields.m_primary_key.end(); it++)
    {
      if (it != fields.m_primary_key.begin())
        my_b_printf(file, ", ");

      // Print column name or column index
      if (it->first >= fields.m_column_name.size())
        my_b_printf(file, "%u", it->first);
      else
        my_b_printf(file, "%s", fields.m_column_name[it->first].c_str());

      // Print prefix length
      if (it->second != 0)
        my_b_printf(file, "(%u)", it->second);
    }

    my_b_printf(file, ")\n");
  }
}

3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626

bool Write_rows_log_event::print(FILE *file, PRINT_EVENT_INFO* print_event_info)
{
  DBUG_EXECUTE_IF("simulate_cache_read_error",
                  {DBUG_SET("+d,simulate_my_b_fill_error");});
  return Rows_log_event::print_helper(file, print_event_info, is_flashback ? "Delete_rows" : "Write_rows");
}

bool Write_rows_compressed_log_event::print(FILE *file,
                                            PRINT_EVENT_INFO* print_event_info)
{
3627
  uchar *new_buf;
3628 3629 3630 3631
  ulong len;
  bool is_malloc = false;
  if(!row_log_event_uncompress(glob_description_event,
                               checksum_alg == BINLOG_CHECKSUM_ALG_CRC32,
3632 3633
                               temp_buf, UINT_MAX32, NULL, 0, &is_malloc,
                               &new_buf, &len))
3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663
  {
    free_temp_buf();
    register_temp_buf(new_buf, true);
    if (Rows_log_event::print_helper(file, print_event_info,
                                     "Write_compressed_rows"))
      goto err;
  }
  else
  {
    if (my_b_printf(&print_event_info->head_cache,
                    "ERROR: uncompress write_compressed_rows failed\n"))
      goto err;
  }

  return 0;
err:
  return 1;
}


bool Delete_rows_log_event::print(FILE *file,
                                  PRINT_EVENT_INFO* print_event_info)
{
  return Rows_log_event::print_helper(file, print_event_info, is_flashback ? "Write_rows" : "Delete_rows");
}


bool Delete_rows_compressed_log_event::print(FILE *file,
                                             PRINT_EVENT_INFO* print_event_info)
{
3664
  uchar *new_buf;
3665 3666 3667 3668
  ulong len;
  bool is_malloc = false;
  if(!row_log_event_uncompress(glob_description_event,
                               checksum_alg == BINLOG_CHECKSUM_ALG_CRC32,
3669 3670
                               temp_buf, UINT_MAX32, NULL, 0, &is_malloc,
                               &new_buf, &len))
3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700
  {
    free_temp_buf();
    register_temp_buf(new_buf, true);
    if (Rows_log_event::print_helper(file, print_event_info,
                                     "Delete_compressed_rows"))
      goto err;
  }
  else
  {
    if (my_b_printf(&print_event_info->head_cache,
                    "ERROR: uncompress delete_compressed_rows failed\n"))
      goto err;
  }

  return 0;
err:
  return 1;
}


bool Update_rows_log_event::print(FILE *file,
				  PRINT_EVENT_INFO* print_event_info)
{
  return Rows_log_event::print_helper(file, print_event_info, "Update_rows");
}

bool
Update_rows_compressed_log_event::print(FILE *file,
                                        PRINT_EVENT_INFO *print_event_info)
{
3701
  uchar *new_buf;
3702 3703 3704 3705
  ulong len;
  bool is_malloc= false;
  if(!row_log_event_uncompress(glob_description_event,
                               checksum_alg == BINLOG_CHECKSUM_ALG_CRC32,
3706 3707
                               temp_buf, UINT_MAX32, NULL, 0, &is_malloc,
                               &new_buf, &len))
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779
  {
    free_temp_buf();
    register_temp_buf(new_buf, true);
    if (Rows_log_event::print_helper(file, print_event_info,
                                     "Update_compressed_rows"))
      goto err;
  }
  else
  {
    if (my_b_printf(&print_event_info->head_cache,
                    "ERROR: uncompress update_compressed_rows failed\n"))
      goto err;
  }

  return 0;
err:
  return 1;
}


bool Incident_log_event::print(FILE *file,
                               PRINT_EVENT_INFO *print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  Write_on_release_cache cache(&print_event_info->head_cache, file);

  if (print_header(&cache, print_event_info, FALSE) ||
      my_b_printf(&cache, "\n# Incident: %s\nRELOAD DATABASE; # Shall generate syntax error\n", description()))
    return 1;
  return cache.flush_data();
}


/* Print for its unrecognized ignorable event */
bool Ignorable_log_event::print(FILE *file,
                                PRINT_EVENT_INFO *print_event_info)
{
  if (print_event_info->short_form)
    return 0;

  if (print_header(&print_event_info->head_cache, print_event_info, FALSE) ||
      my_b_printf(&print_event_info->head_cache, "\tIgnorable\n") ||
      my_b_printf(&print_event_info->head_cache,
                  "# Ignorable event type %d (%s)\n", number, description) ||
      copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
                                          file))
    return 1;
  return 0;
}


/**
  The default values for these variables should be values that are
  *incorrect*, i.e., values that cannot occur in an event.  This way,
  they will always be printed for the first event.
*/
st_print_event_info::st_print_event_info()
{
  myf const flags = MYF(MY_WME | MY_NABP);
  /*
    Currently we only use static PRINT_EVENT_INFO objects, so zeroed at
    program's startup, but these explicit bzero() is for the day someone
    creates dynamic instances.
  */
  bzero(db, sizeof(db));
  bzero(charset, sizeof(charset));
  bzero(time_zone_str, sizeof(time_zone_str));
  delimiter[0]= ';';
  delimiter[1]= 0;
  flags2_inited= 0;
3780
  flags2= 0;
3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805
  sql_mode_inited= 0;
  row_events= 0;
  sql_mode= 0;
  auto_increment_increment= 0;
  auto_increment_offset= 0;
  charset_inited= 0;
  lc_time_names_number= ~0;
  charset_database_number= ILLEGAL_CHARSET_INFO_NUMBER;
  thread_id= 0;
  server_id= 0;
  domain_id= 0;
  thread_id_printed= false;
  server_id_printed= false;
  domain_id_printed= false;
  allow_parallel= true;
  allow_parallel_printed= false;
  found_row_event= false;
  print_row_count= false;
  short_form= false;
  skip_replication= 0;
  printed_fd_event=FALSE;
  file= 0;
  base64_output_mode=BASE64_OUTPUT_UNSPEC;
  open_cached_file(&head_cache, NULL, NULL, 0, flags);
  open_cached_file(&body_cache, NULL, NULL, 0, flags);
Marko Mäkelä's avatar
Marko Mäkelä committed
3806
  open_cached_file(&tail_cache, NULL, NULL, 0, flags);
3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
#ifdef WHEN_FLASHBACK_REVIEW_READY
  open_cached_file(&review_sql_cache, NULL, NULL, 0, flags);
#endif
}


bool copy_event_cache_to_string_and_reinit(IO_CACHE *cache, LEX_STRING *to)
{
  reinit_io_cache(cache, READ_CACHE, 0L, FALSE, FALSE);
  if (cache->end_of_file > SIZE_T_MAX ||
3817
      !(to->str= (char*) my_malloc(PSI_NOT_INSTRUMENTED, (to->length= (size_t)cache->end_of_file), MYF(0))))
3818 3819 3820 3821 3822 3823 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 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907
  {
    perror("Out of memory: can't allocate memory in copy_event_cache_to_string_and_reinit().");
    goto err;
  }
  if (my_b_read(cache, (uchar*) to->str, to->length))
  {
    my_free(to->str);
    perror("Can't read data from IO_CACHE");
    return true;
  }
  reinit_io_cache(cache, WRITE_CACHE, 0, FALSE, TRUE);
  return false;

err:
  to->str= 0;
  to->length= 0;
  return true;
}


bool
Gtid_log_event::print(FILE *file, PRINT_EVENT_INFO *print_event_info)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F, this);
  char buf[21];
  char buf2[21];

  if (!print_event_info->short_form && !is_flashback)
  {
    print_header(&cache, print_event_info, FALSE);
    longlong10_to_str(seq_no, buf, 10);
    if (my_b_printf(&cache, "\tGTID %u-%u-%s", domain_id, server_id, buf))
      goto err;
    if (flags2 & FL_GROUP_COMMIT_ID)
    {
      longlong10_to_str(commit_id, buf2, 10);
      if (my_b_printf(&cache, " cid=%s", buf2))
        goto err;
    }
    if (flags2 & FL_DDL)
      if (my_b_write_string(&cache, " ddl"))
        goto err;
    if (flags2 & FL_TRANSACTIONAL)
      if (my_b_write_string(&cache, " trans"))
        goto err;
    if (flags2 & FL_WAITED)
      if (my_b_write_string(&cache, " waited"))
        goto err;
    if (my_b_printf(&cache, "\n"))
      goto err;

    if (!print_event_info->allow_parallel_printed ||
        print_event_info->allow_parallel != !!(flags2 & FL_ALLOW_PARALLEL))
    {
      if (my_b_printf(&cache,
                  "/*!100101 SET @@session.skip_parallel_replication=%u*/%s\n",
                      !(flags2 & FL_ALLOW_PARALLEL),
                      print_event_info->delimiter))
        goto err;
      print_event_info->allow_parallel= !!(flags2 & FL_ALLOW_PARALLEL);
      print_event_info->allow_parallel_printed= true;
    }

    if (!print_event_info->domain_id_printed ||
        print_event_info->domain_id != domain_id)
    {
      if (my_b_printf(&cache,
                      "/*!100001 SET @@session.gtid_domain_id=%u*/%s\n",
                      domain_id, print_event_info->delimiter))
        goto err;
      print_event_info->domain_id= domain_id;
      print_event_info->domain_id_printed= true;
    }

    if (!print_event_info->server_id_printed ||
        print_event_info->server_id != server_id)
    {
      if (my_b_printf(&cache, "/*!100001 SET @@session.server_id=%u*/%s\n",
                      server_id, print_event_info->delimiter))
        goto err;
      print_event_info->server_id= server_id;
      print_event_info->server_id_printed= true;
    }

    if (!is_flashback)
      if (my_b_printf(&cache, "/*!100001 SET @@session.gtid_seq_no=%s*/%s\n",
                      buf, print_event_info->delimiter))
        goto err;
  }
3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
  if ((flags2 & FL_PREPARED_XA) && !is_flashback)
  {
    my_b_write_string(&cache, "XA START ");
    xid.serialize();
    my_b_write(&cache, (uchar*) xid.buf, strlen(xid.buf));
    if (my_b_printf(&cache, "%s\n", print_event_info->delimiter))
      goto err;
  }
  else if (!(flags2 & FL_STANDALONE))
  {
Marko Mäkelä's avatar
Marko Mäkelä committed
3918 3919
    if (my_b_printf(&cache, is_flashback ? "COMMIT\n%s\n" :
                    "START TRANSACTION\n%s\n", print_event_info->delimiter))
3920
      goto err;
3921
  }
3922 3923 3924 3925 3926

  return cache.flush_data();
err:
  return 1;
}
3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948

bool XA_prepare_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info)
{
  Write_on_release_cache cache(&print_event_info->head_cache, file,
                               Write_on_release_cache::FLUSH_F, this);
  m_xid.serialize();

  if (!print_event_info->short_form)
  {
    print_header(&cache, print_event_info, FALSE);
    if (my_b_printf(&cache, "\tXID = %s\n", m_xid.buf))
      goto error;
  }

  if (my_b_printf(&cache, "XA PREPARE %s\n%s\n",
                   m_xid.buf, print_event_info->delimiter))
    goto error;

  return cache.flush_data();
error:
  return TRUE;
}