1 /* Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
2 
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License, version 2.0,
5    as published by the Free Software Foundation.
6 
7    This program is also distributed with certain software (including
8    but not limited to OpenSSL) that is licensed under separate terms,
9    as designated in a particular file or component or in included license
10    documentation.  The authors of MySQL hereby grant you an additional
11    permission to link the program and your derivative works with the
12    separately licensed software that they have included with MySQL.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License, version 2.0, for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
22 
23 /**
24   @addtogroup Replication
25   @{
26 
27   @file
28 
29   @brief Binary log event definitions.  This includes generic code
30   common to all types of log events, as well as specific code for each
31   type of log event.
32 */
33 
34 
35 #ifndef _log_event_h
36 #define _log_event_h
37 
38 #include <my_bitmap.h>
39 #include "rpl_constants.h"
40 #include "table_id.h"
41 #include <set>
42 
43 #ifdef MYSQL_CLIENT
44 #include "sql_const.h"
45 #include "rpl_utility.h"
46 #include "hash.h"
47 #include "rpl_tblmap.h"
48 #endif
49 
50 #ifdef MYSQL_SERVER
51 #include "rpl_record.h"
52 #include "rpl_reporting.h"
53 #include "sql_class.h"                          /* THD */
54 #include "rpl_utility.h"                        /* Hash_slave_rows */
55 #include "rpl_filter.h"
56 #include "key.h"                                /* key_copy, compare_keys */
57 #endif
58 
59 /* Forward declarations */
60 class String;
61 typedef ulonglong sql_mode_t;
62 typedef struct st_db_worker_hash_entry db_worker_hash_entry;
63 #if defined(HAVE_REPLICATION) && !defined(MYSQL_CLIENT)
64 int ignored_error_code(int err_code);
65 #endif
66 #define PREFIX_SQL_LOAD "SQL_LOAD-"
67 
68 /**
69    Maximum length of the name of a temporary file
70    PREFIX LENGTH - 9
71    UUID          - UUID_LENGTH
72    SEPARATORS    - 2
73    SERVER ID     - 10 (range of server ID 1 to (2^32)-1 = 4,294,967,295)
74    FILE ID       - 10 (uint)
75    EXTENSION     - 7  (Assuming that the extension is always less than 7
76                        characters)
77 */
78 #define TEMP_FILE_MAX_LEN UUID_LENGTH+38
79 
80 /**
81    Either assert or return an error.
82 
83    In debug build, the condition will be checked, but in non-debug
84    builds, the error code given will be returned instead.
85 
86    @param COND   Condition to check
87    @param ERRNO  Error number to return in non-debug builds
88 */
89 #ifdef DBUG_OFF
90 #define ASSERT_OR_RETURN_ERROR(COND, ERRNO) \
91   do { if (!(COND)) return ERRNO; } while (0)
92 #else
93 #define ASSERT_OR_RETURN_ERROR(COND, ERRNO) \
94   DBUG_ASSERT(COND)
95 #endif
96 
97 #define LOG_READ_EOF    -1
98 #define LOG_READ_BOGUS  -2
99 #define LOG_READ_IO     -3
100 #define LOG_READ_MEM    -5
101 #define LOG_READ_TRUNC  -6
102 #define LOG_READ_TOO_LARGE -7
103 #define LOG_READ_CHECKSUM_FAILURE -8
104 
105 #define LOG_EVENT_OFFSET 4
106 
107 /*
108    3 is MySQL 4.x; 4 is MySQL 5.0.0.
109    Compared to version 3, version 4 has:
110    - a different Start_log_event, which includes info about the binary log
111    (sizes of headers); this info is included for better compatibility if the
112    master's MySQL version is different from the slave's.
113    - all events have a unique ID (the triplet (server_id, timestamp at server
114    start, other) to be sure an event is not executed more than once in a
115    multimaster setup, example:
116                 M1
117               /   \
118              v     v
119              M2    M3
120              \     /
121               v   v
122                 S
123    if a query is run on M1, it will arrive twice on S, so we need that S
124    remembers the last unique ID it has processed, to compare and know if the
125    event should be skipped or not. Example of ID: we already have the server id
126    (4 bytes), plus:
127    timestamp_when_the_master_started (4 bytes), a counter (a sequence number
128    which increments every time we write an event to the binlog) (3 bytes).
129    Q: how do we handle when the counter is overflowed and restarts from 0 ?
130 
131    - Query and Load (Create or Execute) events may have a more precise
132      timestamp (with microseconds), number of matched/affected/warnings rows
133    and fields of session variables: SQL_MODE,
134    FOREIGN_KEY_CHECKS, UNIQUE_CHECKS, SQL_AUTO_IS_NULL, the collations and
135    charsets, the PASSWORD() version (old/new/...).
136 */
137 #define BINLOG_VERSION    4
138 
139 /*
140  We could have used SERVER_VERSION_LENGTH, but this introduces an
141  obscure dependency - if somebody decided to change SERVER_VERSION_LENGTH
142  this would break the replication protocol
143 */
144 #define ST_SERVER_VER_LEN 50
145 
146 /*
147   These are flags and structs to handle all the LOAD DATA INFILE options (LINES
148   TERMINATED etc).
149 */
150 
151 /*
152   These are flags and structs to handle all the LOAD DATA INFILE options (LINES
153   TERMINATED etc).
154   DUMPFILE_FLAG is probably useless (DUMPFILE is a clause of SELECT, not of LOAD
155   DATA).
156 */
157 #define DUMPFILE_FLAG		0x1
158 #define OPT_ENCLOSED_FLAG	0x2
159 #define REPLACE_FLAG		0x4
160 #define IGNORE_FLAG		0x8
161 
162 #define FIELD_TERM_EMPTY	0x1
163 #define ENCLOSED_EMPTY		0x2
164 #define LINE_TERM_EMPTY		0x4
165 #define LINE_START_EMPTY	0x8
166 #define ESCAPED_EMPTY		0x10
167 
168 /*****************************************************************************
169 
170   old_sql_ex struct
171 
172  ****************************************************************************/
173 struct old_sql_ex
174 {
175   char field_term;
176   char enclosed;
177   char line_term;
178   char line_start;
179   char escaped;
180   char opt_flags;
181   char empty_flags;
182 };
183 
184 #define NUM_LOAD_DELIM_STRS 5
185 
186 /*****************************************************************************
187 
188   sql_ex_info struct
189 
190  ****************************************************************************/
191 struct sql_ex_info
192 {
sql_ex_infosql_ex_info193   sql_ex_info() {}                            /* Remove gcc warning */
194   const char* field_term;
195   const char* enclosed;
196   const char* line_term;
197   const char* line_start;
198   const char* escaped;
199   int cached_new_format;
200   uint8 field_term_len,enclosed_len,line_term_len,line_start_len, escaped_len;
201   char opt_flags;
202   char empty_flags;
203 
204   // store in new format even if old is possible
force_new_formatsql_ex_info205   void force_new_format() { cached_new_format = 1;}
data_sizesql_ex_info206   int data_size()
207   {
208     return (new_format() ?
209 	    field_term_len + enclosed_len + line_term_len +
210 	    line_start_len + escaped_len + 6 : 7);
211   }
212   bool write_data(IO_CACHE* file);
213   const char* init(const char* buf, const char* buf_end, bool use_new_format);
new_formatsql_ex_info214   bool new_format()
215   {
216     return ((cached_new_format != -1) ? cached_new_format :
217 	    (cached_new_format=(field_term_len > 1 ||
218 				enclosed_len > 1 ||
219 				line_term_len > 1 || line_start_len > 1 ||
220 				escaped_len > 1)));
221   }
222 };
223 
224 /*****************************************************************************
225 
226   MySQL Binary Log
227 
228   This log consists of events.  Each event has a fixed-length header,
229   possibly followed by a variable length data body.
230 
231   The data body consists of an optional fixed length segment (post-header)
232   and  an optional variable length segment.
233 
234   See the #defines below for the format specifics.
235 
236   The events which really update data are Query_log_event,
237   Execute_load_query_log_event and old Load_log_event and
238   Execute_load_log_event events (Execute_load_query is used together with
239   Begin_load_query and Append_block events to replicate LOAD DATA INFILE.
240   Create_file/Append_block/Execute_load (which includes Load_log_event)
241   were used to replicate LOAD DATA before the 5.0.3).
242 
243  ****************************************************************************/
244 
245 #define LOG_EVENT_HEADER_LEN 19U    /* the fixed header length */
246 #define OLD_HEADER_LEN       13U    /* the fixed header length in 3.23 */
247 /*
248    Fixed header length, where 4.x and 5.0 agree. That is, 5.0 may have a longer
249    header (it will for sure when we have the unique event's ID), but at least
250    the first 19 bytes are the same in 4.x and 5.0. So when we have the unique
251    event's ID, LOG_EVENT_HEADER_LEN will be something like 26, but
252    LOG_EVENT_MINIMAL_HEADER_LEN will remain 19.
253 */
254 #define LOG_EVENT_MINIMAL_HEADER_LEN 19U
255 
256 /* event-specific post-header sizes */
257 // where 3.23, 4.x and 5.0 agree
258 #define QUERY_HEADER_MINIMAL_LEN     (4 + 4 + 1 + 2)
259 // where 5.0 differs: 2 for len of N-bytes vars.
260 #define QUERY_HEADER_LEN     (QUERY_HEADER_MINIMAL_LEN + 2)
261 #define STOP_HEADER_LEN      0
262 #define LOAD_HEADER_LEN      (4 + 4 + 4 + 1 +1 + 4)
263 #define START_V3_HEADER_LEN     (2 + ST_SERVER_VER_LEN + 4)
264 #define ROTATE_HEADER_LEN    8 // this is FROZEN (the Rotate post-header is frozen)
265 #define INTVAR_HEADER_LEN      0
266 #define CREATE_FILE_HEADER_LEN 4
267 #define APPEND_BLOCK_HEADER_LEN 4
268 #define EXEC_LOAD_HEADER_LEN   4
269 #define DELETE_FILE_HEADER_LEN 4
270 #define NEW_LOAD_HEADER_LEN    LOAD_HEADER_LEN
271 #define RAND_HEADER_LEN        0
272 #define USER_VAR_HEADER_LEN    0
273 #define FORMAT_DESCRIPTION_HEADER_LEN (START_V3_HEADER_LEN+1+LOG_EVENT_TYPES)
274 #define XID_HEADER_LEN         0
275 #define BEGIN_LOAD_QUERY_HEADER_LEN APPEND_BLOCK_HEADER_LEN
276 #define ROWS_HEADER_LEN_V1     8
277 #define TABLE_MAP_HEADER_LEN   8
278 #define EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN (4 + 4 + 4 + 1)
279 #define EXECUTE_LOAD_QUERY_HEADER_LEN  (QUERY_HEADER_LEN + EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN)
280 #define INCIDENT_HEADER_LEN    2
281 #define HEARTBEAT_HEADER_LEN   0
282 #define IGNORABLE_HEADER_LEN   0
283 #define ROWS_HEADER_LEN_V2     10
284 
285 /*
286    The maximum number of updated databases that a status of
287    Query-log-event can carry.  It can redefined within a range
288    [1.. OVER_MAX_DBS_IN_EVENT_MTS].
289 */
290 #define MAX_DBS_IN_EVENT_MTS 16
291 
292 /*
293    When the actual number of databases exceeds MAX_DBS_IN_EVENT_MTS
294    the value of OVER_MAX_DBS_IN_EVENT_MTS is is put into the
295    mts_accessed_dbs status.
296 */
297 #define OVER_MAX_DBS_IN_EVENT_MTS 254
298 
299 /*
300   Max number of possible extra bytes in a replication event compared to a
301   packet (i.e. a query) sent from client to master;
302   First, an auxiliary log_event status vars estimation:
303 */
304 #define MAX_SIZE_LOG_EVENT_STATUS (1U + 4          /* type, flags2 */   + \
305                                    1U + 8          /* type, sql_mode */ + \
306                                    1U + 1 + 255    /* type, length, catalog */ + \
307                                    1U + 4          /* type, auto_increment */ + \
308                                    1U + 6          /* type, charset */ + \
309                                    1U + 1 + 255    /* type, length, time_zone */ + \
310                                    1U + 2          /* type, lc_time_names_number */ + \
311                                    1U + 2          /* type, charset_database_number */ + \
312                                    1U + 8          /* type, table_map_for_update */ + \
313                                    1U + 4          /* type, master_data_written */ + \
314                                                    /* type, db_1, db_2, ... */  \
315                                    1U + (MAX_DBS_IN_EVENT_MTS * (1 + NAME_LEN)) + \
316                                    3U +            /* type, microseconds */ + \
317                                    1U + 16 + 1 + 60/* type, user_len, user, host_len, host */)
318 #define MAX_LOG_EVENT_HEADER   ( /* in order of Query_log_event::write */ \
319   LOG_EVENT_HEADER_LEN + /* write_header */ \
320   QUERY_HEADER_LEN     + /* write_data */   \
321   EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN + /*write_post_header_for_derived */ \
322   MAX_SIZE_LOG_EVENT_STATUS + /* status */ \
323   NAME_LEN + 1)
324 
325 /*
326   The new option is added to handle large packets that are sent from the master
327   to the slave. It is used to increase the thd(max_allowed) for both the
328   DUMP thread on the master and the SQL/IO thread on the slave.
329 */
330 #define MAX_MAX_ALLOWED_PACKET 1024*1024*1024
331 
332 /*
333    Event header offsets;
334    these point to places inside the fixed header.
335 */
336 
337 #define EVENT_TYPE_OFFSET    4
338 #define SERVER_ID_OFFSET     5
339 #define EVENT_LEN_OFFSET     9
340 #define LOG_POS_OFFSET       13
341 #define FLAGS_OFFSET         17
342 
343 /* start event post-header (for v3 and v4) */
344 
345 #define ST_BINLOG_VER_OFFSET  0
346 #define ST_SERVER_VER_OFFSET  2
347 #define ST_CREATED_OFFSET     (ST_SERVER_VER_OFFSET + ST_SERVER_VER_LEN)
348 #define ST_COMMON_HEADER_LEN_OFFSET (ST_CREATED_OFFSET + 4)
349 
350 /* slave event post-header (this event is never written) */
351 
352 #define SL_MASTER_PORT_OFFSET   8
353 #define SL_MASTER_POS_OFFSET    0
354 #define SL_MASTER_HOST_OFFSET   10
355 
356 /* query event post-header */
357 
358 #define Q_THREAD_ID_OFFSET	0
359 #define Q_EXEC_TIME_OFFSET	4
360 #define Q_DB_LEN_OFFSET		8
361 #define Q_ERR_CODE_OFFSET	9
362 #define Q_STATUS_VARS_LEN_OFFSET 11
363 #define Q_DATA_OFFSET		QUERY_HEADER_LEN
364 /* these are codes, not offsets; not more than 256 values (1 byte). */
365 #define Q_FLAGS2_CODE           0
366 #define Q_SQL_MODE_CODE         1
367 /*
368   Q_CATALOG_CODE is catalog with end zero stored; it is used only by MySQL
369   5.0.x where 0<=x<=3. We have to keep it to be able to replicate these
370   old masters.
371 */
372 #define Q_CATALOG_CODE          2
373 #define Q_AUTO_INCREMENT	3
374 #define Q_CHARSET_CODE          4
375 #define Q_TIME_ZONE_CODE        5
376 /*
377   Q_CATALOG_NZ_CODE is catalog withOUT end zero stored; it is used by MySQL
378   5.0.x where x>=4. Saves one byte in every Query_log_event in binlog,
379   compared to Q_CATALOG_CODE. The reason we didn't simply re-use
380   Q_CATALOG_CODE is that then a 5.0.3 slave of this 5.0.x (x>=4) master would
381   crash (segfault etc) because it would expect a 0 when there is none.
382 */
383 #define Q_CATALOG_NZ_CODE       6
384 
385 #define Q_LC_TIME_NAMES_CODE    7
386 
387 #define Q_CHARSET_DATABASE_CODE 8
388 
389 #define Q_TABLE_MAP_FOR_UPDATE_CODE 9
390 
391 #define Q_MASTER_DATA_WRITTEN_CODE 10
392 
393 #define Q_INVOKER 11
394 
395 /*
396   Q_UPDATED_DB_NAMES status variable collects of the updated databases
397   total number and their names to be propagated to the slave in order
398   to facilitate the parallel applying of the Query events.
399 */
400 #define Q_UPDATED_DB_NAMES 12
401 
402 #define Q_MICROSECONDS 13
403 
404 #ifndef DBUG_OFF
405 #define Q_QUERY_EXEC_TIME 250
406 #endif
407 
408 /* Intvar event post-header */
409 
410 /* Intvar event data */
411 #define I_TYPE_OFFSET        0
412 #define I_VAL_OFFSET         1
413 
414 /* Rand event data */
415 #define RAND_SEED1_OFFSET 0
416 #define RAND_SEED2_OFFSET 8
417 
418 /* User_var event data */
419 #define UV_VAL_LEN_SIZE        4
420 #define UV_VAL_IS_NULL         1
421 #define UV_VAL_TYPE_SIZE       1
422 #define UV_NAME_LEN_SIZE       4
423 #define UV_CHARSET_NUMBER_SIZE 4
424 
425 /* Load event post-header */
426 #define L_THREAD_ID_OFFSET   0
427 #define L_EXEC_TIME_OFFSET   4
428 #define L_SKIP_LINES_OFFSET  8
429 #define L_TBL_LEN_OFFSET     12
430 #define L_DB_LEN_OFFSET      13
431 #define L_NUM_FIELDS_OFFSET  14
432 #define L_SQL_EX_OFFSET      18
433 #define L_DATA_OFFSET        LOAD_HEADER_LEN
434 
435 /* Rotate event post-header */
436 #define R_POS_OFFSET       0
437 #define R_IDENT_OFFSET     8
438 
439 /* CF to DF handle LOAD DATA INFILE */
440 
441 /* CF = "Create File" */
442 #define CF_FILE_ID_OFFSET  0
443 #define CF_DATA_OFFSET     CREATE_FILE_HEADER_LEN
444 
445 /* AB = "Append Block" */
446 #define AB_FILE_ID_OFFSET  0
447 #define AB_DATA_OFFSET     APPEND_BLOCK_HEADER_LEN
448 
449 /* EL = "Execute Load" */
450 #define EL_FILE_ID_OFFSET  0
451 
452 /* DF = "Delete File" */
453 #define DF_FILE_ID_OFFSET  0
454 
455 /* TM = "Table Map" */
456 #define TM_MAPID_OFFSET    0
457 #define TM_FLAGS_OFFSET    6
458 
459 /* RW = "RoWs" */
460 #define RW_MAPID_OFFSET    0
461 #define RW_FLAGS_OFFSET    6
462 #define RW_VHLEN_OFFSET    8
463 #define RW_V_TAG_LEN       1
464 #define RW_V_EXTRAINFO_TAG 0
465 
466 /* ELQ = "Execute Load Query" */
467 #define ELQ_FILE_ID_OFFSET QUERY_HEADER_LEN
468 #define ELQ_FN_POS_START_OFFSET ELQ_FILE_ID_OFFSET + 4
469 #define ELQ_FN_POS_END_OFFSET ELQ_FILE_ID_OFFSET + 8
470 #define ELQ_DUP_HANDLING_OFFSET ELQ_FILE_ID_OFFSET + 12
471 
472 /* 4 bytes which all binlogs should begin with */
473 #define BINLOG_MAGIC        "\xfe\x62\x69\x6e"
474 
475 /*
476   The 2 flags below were useless :
477   - the first one was never set
478   - the second one was set in all Rotate events on the master, but not used for
479   anything useful.
480   So they are now removed and their place may later be reused for other
481   flags. Then one must remember that Rotate events in 4.x have
482   LOG_EVENT_FORCED_ROTATE_F set, so one should not rely on the value of the
483   replacing flag when reading a Rotate event.
484   I keep the defines here just to remember what they were.
485 */
486 #ifdef TO_BE_REMOVED
487 #define LOG_EVENT_TIME_F            0x1
488 #define LOG_EVENT_FORCED_ROTATE_F   0x2
489 #endif
490 
491 /*
492    This flag only makes sense for Format_description_log_event. It is set
493    when the event is written, and *reset* when a binlog file is
494    closed (yes, it's the only case when MySQL modifies already written
495    part of binlog).  Thus it is a reliable indicator that binlog was
496    closed correctly.  (Stop_log_event is not enough, there's always a
497    small chance that mysqld crashes in the middle of insert and end of
498    the binlog would look like a Stop_log_event).
499 
500    This flag is used to detect a restart after a crash, and to provide
501    "unbreakable" binlog. The problem is that on a crash storage engines
502    rollback automatically, while binlog does not.  To solve this we use this
503    flag and automatically append ROLLBACK to every non-closed binlog (append
504    virtually, on reading, file itself is not changed). If this flag is found,
505    mysqlbinlog simply prints "ROLLBACK" Replication master does not abort on
506    binlog corruption, but takes it as EOF, and replication slave forces a
507    rollback in this case.
508 
509    Note, that old binlogs does not have this flag set, so we get a
510    a backward-compatible behaviour.
511 */
512 
513 #define LOG_EVENT_BINLOG_IN_USE_F       0x1
514 
515 /**
516   @def LOG_EVENT_THREAD_SPECIFIC_F
517 
518   If the query depends on the thread (for example: TEMPORARY TABLE).
519   Currently this is used by mysqlbinlog to know it must print
520   SET @@PSEUDO_THREAD_ID=xx; before the query (it would not hurt to print it
521   for every query but this would be slow).
522 */
523 #define LOG_EVENT_THREAD_SPECIFIC_F 0x4
524 
525 /**
526   @def LOG_EVENT_SUPPRESS_USE_F
527 
528   Suppress the generation of 'USE' statements before the actual
529   statement. This flag should be set for any events that does not need
530   the current database set to function correctly. Most notable cases
531   are 'CREATE DATABASE' and 'DROP DATABASE'.
532 
533   This flags should only be used in exceptional circumstances, since
534   it introduce a significant change in behaviour regarding the
535   replication logic together with the flags --binlog-do-db and
536   --replicated-do-db.
537  */
538 #define LOG_EVENT_SUPPRESS_USE_F    0x8
539 
540 /*
541   Note: this is a place holder for the flag
542   LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F (0x10), which is not used any
543   more, please do not reused this value for other flags.
544  */
545 
546 /**
547    @def LOG_EVENT_ARTIFICIAL_F
548 
549    Artificial events are created arbitarily and not written to binary
550    log
551 
552    These events should not update the master log position when slave
553    SQL thread executes them.
554 */
555 #define LOG_EVENT_ARTIFICIAL_F 0x20
556 
557 /**
558    @def LOG_EVENT_RELAY_LOG_F
559 
560    Events with this flag set are created by slave IO thread and written
561    to relay log
562 */
563 #define LOG_EVENT_RELAY_LOG_F 0x40
564 
565 /**
566    @def LOG_EVENT_IGNORABLE_F
567 
568    For an event, 'e', carrying a type code, that a slave,
569    's', does not recognize, 's' will check 'e' for
570    LOG_EVENT_IGNORABLE_F, and if the flag is set, then 'e'
571    is ignored. Otherwise, 's' acknowledges that it has
572    found an unknown event in the relay log.
573 */
574 #define LOG_EVENT_IGNORABLE_F 0x80
575 
576 /**
577    @def LOG_EVENT_NO_FILTER_F
578 
579    Events with this flag are not filtered (e.g. on the current
580    database) and are always written to the binary log regardless of
581    filters.
582 */
583 #define LOG_EVENT_NO_FILTER_F 0x100
584 
585 /**
586    MTS: group of events can be marked to force its execution
587    in isolation from any other Workers.
588    So it's a marker for Coordinator to memorize and perform necessary
589    operations in order to guarantee no interference from other Workers.
590    The flag can be set ON only for an event that terminates its group.
591    Typically that is done for a transaction that contains
592    a query accessing more than OVER_MAX_DBS_IN_EVENT_MTS databases.
593 */
594 #define LOG_EVENT_MTS_ISOLATE_F 0x200
595 
596 
597 /**
598   @def OPTIONS_WRITTEN_TO_BIN_LOG
599 
600   OPTIONS_WRITTEN_TO_BIN_LOG are the bits of thd->options which must
601   be written to the binlog. OPTIONS_WRITTEN_TO_BIN_LOG could be
602   written into the Format_description_log_event, so that if later we
603   don't want to replicate a variable we did replicate, or the
604   contrary, it's doable. But it should not be too hard to decide once
605   for all of what we replicate and what we don't, among the fixed 32
606   bits of thd->options.
607 
608   I (Guilhem) have read through every option's usage, and it looks
609   like OPTION_AUTO_IS_NULL and OPTION_NO_FOREIGN_KEYS are the only
610   ones which alter how the query modifies the table. It's good to
611   replicate OPTION_RELAXED_UNIQUE_CHECKS too because otherwise, the
612   slave may insert data slower than the master, in InnoDB.
613   OPTION_BIG_SELECTS is not needed (the slave thread runs with
614   max_join_size=HA_POS_ERROR) and OPTION_BIG_TABLES is not needed
615   either, as the manual says (because a too big in-memory temp table
616   is automatically written to disk).
617 */
618 #define OPTIONS_WRITTEN_TO_BIN_LOG \
619   (OPTION_AUTO_IS_NULL | OPTION_NO_FOREIGN_KEY_CHECKS |  \
620    OPTION_RELAXED_UNIQUE_CHECKS | OPTION_NOT_AUTOCOMMIT)
621 
622 /* Shouldn't be defined before */
623 #define EXPECTED_OPTIONS \
624   ((ULL(1) << 14) | (ULL(1) << 26) | (ULL(1) << 27) | (ULL(1) << 19))
625 
626 #if OPTIONS_WRITTEN_TO_BIN_LOG != EXPECTED_OPTIONS
627 #error OPTIONS_WRITTEN_TO_BIN_LOG must NOT change their values!
628 #endif
629 #undef EXPECTED_OPTIONS         /* You shouldn't use this one */
630 
631 enum enum_binlog_checksum_alg {
632   BINLOG_CHECKSUM_ALG_OFF= 0,    // Events are without checksum though its generator
633                                  // is checksum-capable New Master (NM).
634   BINLOG_CHECKSUM_ALG_CRC32= 1,  // CRC32 of zlib algorithm.
635   BINLOG_CHECKSUM_ALG_ENUM_END,  // the cut line: valid alg range is [1, 0x7f].
636   BINLOG_CHECKSUM_ALG_UNDEF= 255 // special value to tag undetermined yet checksum
637                                  // or events from checksum-unaware servers
638 };
639 
640 #define CHECKSUM_CRC32_SIGNATURE_LEN 4
641 /**
642    defined statically while there is just one alg implemented
643 */
644 #define BINLOG_CHECKSUM_LEN CHECKSUM_CRC32_SIGNATURE_LEN
645 #define BINLOG_CHECKSUM_ALG_DESC_LEN 1  /* 1 byte checksum alg descriptor */
646 
647 /**
648   @enum Log_event_type
649 
650   Enumeration type for the different types of log events.
651 */
652 enum Log_event_type
653 {
654   /*
655     Every time you update this enum (when you add a type), you have to
656     fix Format_description_log_event::Format_description_log_event().
657   */
658   UNKNOWN_EVENT= 0,
659   START_EVENT_V3= 1,
660   QUERY_EVENT= 2,
661   STOP_EVENT= 3,
662   ROTATE_EVENT= 4,
663   INTVAR_EVENT= 5,
664   LOAD_EVENT= 6,
665   SLAVE_EVENT= 7,  /* Unused. Slave_log_event code has been removed. (15th Oct. 2010) */
666   CREATE_FILE_EVENT= 8,
667   APPEND_BLOCK_EVENT= 9,
668   EXEC_LOAD_EVENT= 10,
669   DELETE_FILE_EVENT= 11,
670   /*
671     NEW_LOAD_EVENT is like LOAD_EVENT except that it has a longer
672     sql_ex, allowing multibyte TERMINATED BY etc; both types share the
673     same class (Load_log_event)
674   */
675   NEW_LOAD_EVENT= 12,
676   RAND_EVENT= 13,
677   USER_VAR_EVENT= 14,
678   FORMAT_DESCRIPTION_EVENT= 15,
679   XID_EVENT= 16,
680   BEGIN_LOAD_QUERY_EVENT= 17,
681   EXECUTE_LOAD_QUERY_EVENT= 18,
682 
683   TABLE_MAP_EVENT = 19,
684 
685   /*
686     These event numbers were used for 5.1.0 to 5.1.15 and are
687     therefore obsolete.
688    */
689   PRE_GA_WRITE_ROWS_EVENT = 20,
690   PRE_GA_UPDATE_ROWS_EVENT = 21,
691   PRE_GA_DELETE_ROWS_EVENT = 22,
692 
693   /*
694     These event numbers are used from 5.1.16 until mysql-trunk-xx
695    */
696   WRITE_ROWS_EVENT_V1 = 23,
697   UPDATE_ROWS_EVENT_V1 = 24,
698   DELETE_ROWS_EVENT_V1 = 25,
699 
700   /*
701     Something out of the ordinary happened on the master
702    */
703   INCIDENT_EVENT= 26,
704 
705   /*
706     Heartbeat event to be send by master at its idle time
707     to ensure master's online status to slave
708   */
709   HEARTBEAT_LOG_EVENT= 27,
710 
711   /*
712     In some situations, it is necessary to send over ignorable
713     data to the slave: data that a slave can handle in case there
714     is code for handling it, but which can be ignored if it is not
715     recognized.
716   */
717   IGNORABLE_LOG_EVENT= 28,
718   ROWS_QUERY_LOG_EVENT= 29,
719 
720   /* Version 2 of the Row events */
721   WRITE_ROWS_EVENT = 30,
722   UPDATE_ROWS_EVENT = 31,
723   DELETE_ROWS_EVENT = 32,
724 
725   GTID_LOG_EVENT= 33,
726   ANONYMOUS_GTID_LOG_EVENT= 34,
727 
728   PREVIOUS_GTIDS_LOG_EVENT= 35,
729   /*
730     Add new events here - right above this comment!
731     Existing events (except ENUM_END_EVENT) should never change their numbers
732   */
733 
734   ENUM_END_EVENT /* end marker */
735 };
736 
737 /*
738    The number of types we handle in Format_description_log_event (UNKNOWN_EVENT
739    is not to be handled, it does not exist in binlogs, it does not have a
740    format).
741 */
742 #define LOG_EVENT_TYPES (ENUM_END_EVENT-1)
743 
744 enum Int_event_type
745 {
746   INVALID_INT_EVENT = 0, LAST_INSERT_ID_EVENT = 1, INSERT_ID_EVENT = 2
747 };
748 
749 
750 #ifdef MYSQL_SERVER
751 class String;
752 class MYSQL_BIN_LOG;
753 class THD;
754 #endif
755 
756 class Format_description_log_event;
757 class Relay_log_info;
758 class Slave_worker;
759 class Slave_committed_queue;
760 
761 #ifdef MYSQL_CLIENT
762 enum enum_base64_output_mode {
763   BASE64_OUTPUT_NEVER= 0,
764   BASE64_OUTPUT_AUTO= 1,
765   BASE64_OUTPUT_UNSPEC= 2,
766   BASE64_OUTPUT_DECODE_ROWS= 3,
767   /* insert new output modes here */
768   BASE64_OUTPUT_MODE_COUNT
769 };
770 
771 /*
772   A structure for mysqlbinlog to know how to print events
773 
774   This structure is passed to the event's print() methods,
775 
776   There are two types of settings stored here:
777   1. Last db, flags2, sql_mode etc comes from the last printed event.
778      They are stored so that only the necessary USE and SET commands
779      are printed.
780   2. Other information on how to print the events, e.g. short_form,
781      hexdump_from.  These are not dependent on the last event.
782 */
783 typedef struct st_print_event_info
784 {
785   /*
786     Settings for database, sql_mode etc that comes from the last event
787     that was printed.  We cache these so that we don't have to print
788     them if they are unchanged.
789   */
790   // TODO: have the last catalog here ??
791   char db[FN_REFLEN+1]; // TODO: make this a LEX_STRING when thd->db is
792   bool flags2_inited;
793   uint32 flags2;
794   bool sql_mode_inited;
795   sql_mode_t sql_mode;		/* must be same as THD.variables.sql_mode */
796   ulong auto_increment_increment, auto_increment_offset;
797   bool charset_inited;
798   char charset[6]; // 3 variables, each of them storable in 2 bytes
799   char time_zone_str[MAX_TIME_ZONE_NAME_LENGTH];
800   uint lc_time_names_number;
801   uint charset_database_number;
802   uint thread_id;
803   bool thread_id_printed;
804   uint32 server_id_from_fd_event;
805 
806   st_print_event_info();
807 
~st_print_event_infost_print_event_info808   ~st_print_event_info() {
809     close_cached_file(&head_cache);
810     close_cached_file(&body_cache);
811   }
init_okst_print_event_info812   bool init_ok() /* tells if construction was successful */
813     { return my_b_inited(&head_cache) && my_b_inited(&body_cache); }
814 
815 
816   /* Settings on how to print the events */
817   bool short_form;
818   enum_base64_output_mode base64_output_mode;
819   /*
820     This is set whenever a Format_description_event is printed.
821     Later, when an event is printed in base64, this flag is tested: if
822     no Format_description_event has been seen, it is unsafe to print
823     the base64 event, so an error message is generated.
824   */
825   bool printed_fd_event;
826   my_off_t hexdump_from;
827   uint8 common_header_len;
828   char delimiter[16];
829 
830   uint verbose;
831   table_mapping m_table_map;
832   table_mapping m_table_map_ignored;
833 
834   /*
835      These two caches are used by the row-based replication events to
836      collect the header information and the main body of the events
837      making up a statement.
838    */
839   IO_CACHE head_cache;
840   IO_CACHE body_cache;
841   /* Indicate if the body cache has unflushed events */
842   bool have_unflushed_events;
843 
844   /*
845      True if an event was skipped while printing the events of
846      a transaction and no COMMIT statement or XID event was ever
847      output (ie, was filtered out as well). This can be triggered
848      by the --database option of mysqlbinlog.
849 
850      False, otherwise.
851    */
852   bool skipped_event_in_transaction;
853 
854   /* true if gtid_next is set with a value */
855   bool is_gtid_next_set;
856 
857   /*
858     Determines if the current value of gtid_next needs to be restored
859     to AUTOMATIC if the binary log would end after the current event.
860 
861     If the log ends after a transaction, then this should be false.
862     If the log ends in the middle of a transaction, then this should
863     be true; this can happen for relay logs where transactions are
864     split over multiple logs.
865 
866     Set to true initially, and after a Gtid_log_event is processed.
867     Set to false if is_gtid_next_set is true.
868    */
869   bool is_gtid_next_valid;
870 } PRINT_EVENT_INFO;
871 #endif
872 
873 /*
874   A specific to the database-scheduled MTS type.
875 */
876 typedef struct st_mts_db_names
877 {
878   const char *name[MAX_DBS_IN_EVENT_MTS];
879   int  num;
880 } Mts_db_names;
881 
882 
883 /**
884   @class Log_event
885 
886   This is the abstract base class for binary log events.
887 
888   @section Log_event_binary_format Binary Format
889 
890   Any @c Log_event saved on disk consists of the following three
891   components.
892 
893   - Common-Header
894   - Post-Header
895   - Body
896 
897   The Common-Header, documented in the table @ref Table_common_header
898   "below", always has the same form and length within one version of
899   MySQL.  Each event type specifies a format and length of the
900   Post-Header.  The length of the Common-Header is the same for all
901   events of the same type.  The Body may be of different format and
902   length even for different events of the same type.  The binary
903   formats of Post-Header and Body are documented separately in each
904   subclass.  The binary format of Common-Header is as follows.
905 
906   <table>
907   <caption>Common-Header</caption>
908 
909   <tr>
910     <th>Name</th>
911     <th>Format</th>
912     <th>Description</th>
913   </tr>
914 
915   <tr>
916     <td>timestamp</td>
917     <td>4 byte unsigned integer</td>
918     <td>The time when the query started, in seconds since 1970.
919     </td>
920   </tr>
921 
922   <tr>
923     <td>type</td>
924     <td>1 byte enumeration</td>
925     <td>See enum #Log_event_type.</td>
926   </tr>
927 
928   <tr>
929     <td>server_id</td>
930     <td>4 byte unsigned integer</td>
931     <td>Server ID of the server that created the event.</td>
932   </tr>
933 
934   <tr>
935     <td>total_size</td>
936     <td>4 byte unsigned integer</td>
937     <td>The total size of this event, in bytes.  In other words, this
938     is the sum of the sizes of Common-Header, Post-Header, and Body.
939     </td>
940   </tr>
941 
942   <tr>
943     <td>master_position</td>
944     <td>4 byte unsigned integer</td>
945     <td>The position of the next event in the master binary log, in
946     bytes from the beginning of the file.  In a binlog that is not a
947     relay log, this is just the position of the next event, in bytes
948     from the beginning of the file.  In a relay log, this is
949     the position of the next event in the master's binlog.
950     </td>
951   </tr>
952 
953   <tr>
954     <td>flags</td>
955     <td>2 byte bitfield</td>
956     <td>See Log_event::flags.</td>
957   </tr>
958   </table>
959 
960   Summing up the numbers above, we see that the total size of the
961   common header is 19 bytes.
962 
963   @subsection Log_event_format_of_atomic_primitives Format of Atomic Primitives
964 
965   - All numbers, whether they are 16-, 24-, 32-, or 64-bit numbers,
966   are stored in little endian, i.e., the least significant byte first,
967   unless otherwise specified.
968 
969   @anchor packed_integer
970   - Some events use a special format for efficient representation of
971   unsigned integers, called Packed Integer.  A Packed Integer has the
972   capacity of storing up to 8-byte integers, while small integers
973   still can use 1, 3, or 4 bytes.  The value of the first byte
974   determines how to read the number, according to the following table:
975 
976   <table>
977   <caption>Format of Packed Integer</caption>
978 
979   <tr>
980     <th>First byte</th>
981     <th>Format</th>
982   </tr>
983 
984   <tr>
985     <td>0-250</td>
986     <td>The first byte is the number (in the range 0-250), and no more
987     bytes are used.</td>
988   </tr>
989 
990   <tr>
991     <td>252</td>
992     <td>Two more bytes are used.  The number is in the range
993     251-0xffff.</td>
994   </tr>
995 
996   <tr>
997     <td>253</td>
998     <td>Three more bytes are used.  The number is in the range
999     0xffff-0xffffff.</td>
1000   </tr>
1001 
1002   <tr>
1003     <td>254</td>
1004     <td>Eight more bytes are used.  The number is in the range
1005     0xffffff-0xffffffffffffffff.</td>
1006   </tr>
1007 
1008   </table>
1009 
1010   - Strings are stored in various formats.  The format of each string
1011   is documented separately.
1012 */
1013 class Log_event
1014 {
1015 public:
1016   /**
1017      Enumeration of what kinds of skipping (and non-skipping) that can
1018      occur when the slave executes an event.
1019 
1020      @see shall_skip
1021      @see do_shall_skip
1022    */
1023   enum enum_skip_reason {
1024     /**
1025        Don't skip event.
1026     */
1027     EVENT_SKIP_NOT,
1028 
1029     /**
1030        Skip event by ignoring it.
1031 
1032        This means that the slave skip counter will not be changed.
1033     */
1034     EVENT_SKIP_IGNORE,
1035 
1036     /**
1037        Skip event and decrease skip counter.
1038     */
1039     EVENT_SKIP_COUNT
1040   };
1041 
1042 protected:
1043   enum enum_event_cache_type
1044   {
1045     EVENT_INVALID_CACHE= 0,
1046     /*
1047       If possible the event should use a non-transactional cache before
1048       being flushed to the binary log. This means that it must be flushed
1049       right after its correspondent statement is completed.
1050     */
1051     EVENT_STMT_CACHE,
1052     /*
1053       The event should use a transactional cache before being flushed to
1054       the binary log. This means that it must be flushed upon commit or
1055       rollback.
1056     */
1057     EVENT_TRANSACTIONAL_CACHE,
1058     /*
1059       The event must be written directly to the binary log without going
1060       through any cache.
1061     */
1062     EVENT_NO_CACHE,
1063     /*
1064        If there is a need for different types, introduce them before this.
1065     */
1066     EVENT_CACHE_COUNT
1067   };
1068 
1069   enum enum_event_logging_type
1070   {
1071     EVENT_INVALID_LOGGING= 0,
1072     /*
1073       The event must be written to a cache and upon commit or rollback
1074       written to the binary log.
1075     */
1076     EVENT_NORMAL_LOGGING,
1077     /*
1078       The event must be written to an empty cache and immediatly written
1079       to the binary log without waiting for any other event.
1080     */
1081     EVENT_IMMEDIATE_LOGGING,
1082     /*
1083        If there is a need for different types, introduce them before this.
1084     */
1085     EVENT_CACHE_LOGGING_COUNT
1086   };
1087 
1088 public:
1089   /*
1090     The following type definition is to be used whenever data is placed
1091     and manipulated in a common buffer. Use this typedef for buffers
1092     that contain data containing binary and character data.
1093   */
1094   typedef unsigned char Byte;
1095 
1096   /*
1097     The offset in the log where this event originally appeared (it is
1098     preserved in relay logs, making SHOW SLAVE STATUS able to print
1099     coordinates of the event in the master's binlog). Note: when a
1100     transaction is written by the master to its binlog (wrapped in
1101     BEGIN/COMMIT) the log_pos of all the queries it contains is the
1102     one of the BEGIN (this way, when one does SHOW SLAVE STATUS it
1103     sees the offset of the BEGIN, which is logical as rollback may
1104     occur), except the COMMIT query which has its real offset.
1105   */
1106   my_off_t log_pos;
1107   /*
1108      A temp buffer for read_log_event; it is later analysed according to the
1109      event's type, and its content is distributed in the event-specific fields.
1110   */
1111   char *temp_buf;
1112   /*
1113     Timestamp on the master(for debugging and replication of
1114     NOW()/TIMESTAMP).  It is important for queries and LOAD DATA
1115     INFILE. This is set at the event's creation time, except for Query
1116     and Load (et al.) events where this is set at the query's
1117     execution time, which guarantees good replication (otherwise, we
1118     could have a query and its event with different timestamps).
1119   */
1120   struct timeval when;
1121   /* The number of seconds the query took to run on the master. */
1122   ulong exec_time;
1123   /* Number of bytes written by write() function */
1124   ulong data_written;
1125 
1126   /*
1127     The master's server id (is preserved in the relay log; used to
1128     prevent from infinite loops in circular replication).
1129   */
1130   uint32 server_id;
1131 
1132   /*
1133     The server id read from the Binlog.  server_id above has
1134     lowest bits of this only according to the value of
1135     opt_server_id_bits
1136   */
1137   uint32 unmasked_server_id;
1138 
1139   /**
1140     Some 16 flags. See the definitions above for LOG_EVENT_TIME_F,
1141     LOG_EVENT_FORCED_ROTATE_F, LOG_EVENT_THREAD_SPECIFIC_F, and
1142     LOG_EVENT_SUPPRESS_USE_F for notes.
1143   */
1144   uint16 flags;
1145 
1146   /**
1147     A storage to cache the global system variable's value.
1148     Handling of a separate event will be governed its member.
1149   */
1150   ulong slave_exec_mode;
1151 
1152   /**
1153     Defines the type of the cache, if any, where the event will be
1154     stored before being flushed to disk.
1155   */
1156   enum_event_cache_type event_cache_type;
1157 
1158   /**
1159     Defines when information, i.e. event or cache, will be flushed
1160     to disk.
1161   */
1162   enum_event_logging_type event_logging_type;
1163 
1164   /**
1165     Placeholder for event checksum while writing to binlog.
1166   */
1167   ha_checksum crc;
1168 
1169   /**
1170     Index in @c rli->gaq array to indicate a group that this event is
1171     purging. The index is set by Coordinator to a group terminator
1172     event is checked by Worker at the event execution. The indexed
1173     data represent the Worker progress status.
1174   */
1175   ulong mts_group_idx;
1176 
1177   /**
1178     MTS: associating the event with either an assigned Worker or Coordinator.
1179     Additionally the member serves to tag deferred (IRU) events to avoid
1180     the event regular time destruction.
1181   */
1182   Relay_log_info *worker;
1183 
1184   /**
1185     A copy of the main rli value stored into event to pass to MTS worker rli
1186   */
1187   ulonglong future_event_relay_log_pos;
1188 
1189 #ifdef MYSQL_SERVER
1190   THD* thd;
1191   /**
1192      Partition info associate with event to deliver to MTS event applier
1193   */
1194   db_worker_hash_entry *mts_assigned_partitions[MAX_DBS_IN_EVENT_MTS];
1195 
1196   Log_event(enum_event_cache_type cache_type_arg= EVENT_INVALID_CACHE,
1197             enum_event_logging_type logging_type_arg= EVENT_INVALID_LOGGING);
1198   Log_event(THD* thd_arg, uint16 flags_arg,
1199             enum_event_cache_type cache_type_arg,
1200             enum_event_logging_type logging_type_arg);
1201   /*
1202     read_log_event() functions read an event from a binlog or relay
1203     log; used by SHOW BINLOG EVENTS, the binlog_dump thread on the
1204     master (reads master's binlog), the slave IO thread (reads the
1205     event sent by binlog_dump), the slave SQL thread (reads the event
1206     from the relay log).  If mutex is 0, the read will proceed without
1207     mutex.  We need the description_event to be able to parse the
1208     event (to know the post-header's size); in fact in read_log_event
1209     we detect the event's type, then call the specific event's
1210     constructor and pass description_event as an argument.
1211   */
1212   static Log_event* read_log_event(IO_CACHE* file,
1213                                    mysql_mutex_t* log_lock,
1214                                    const Format_description_log_event
1215                                    *description_event,
1216                                    my_bool crc_check);
1217 
1218   /**
1219     Reads an event from a binlog or relay log. Used by the dump thread
1220     this method reads the event into a raw buffer without parsing it.
1221 
1222     @Note If mutex is 0, the read will proceed without mutex.
1223 
1224     @Note If a log name is given than the method will check if the
1225     given binlog is still active.
1226 
1227     @param[in]  file                log file to be read
1228     @param[out] packet              packet to hold the event
1229     @param[in]  lock                the lock to be used upon read
1230     @param[in]  checksum_alg_arg    the checksum algorithm
1231     @param[in]  log_file_name_arg   the log's file name
1232     @param[out] is_binlog_active    is the current log still active
1233 
1234     @retval 0                   success
1235     @retval LOG_READ_EOF        end of file, nothing was read
1236     @retval LOG_READ_BOGUS      malformed event
1237     @retval LOG_READ_IO         io error while reading
1238     @retval LOG_READ_MEM        packet memory allocation failed
1239     @retval LOG_READ_TRUNC      only a partial event could be read
1240     @retval LOG_READ_TOO_LARGE  event too large
1241    */
1242   static int read_log_event(IO_CACHE* file, String* packet,
1243                             mysql_mutex_t* log_lock,
1244                             uint8 checksum_alg_arg,
1245                             const char *log_file_name_arg= NULL,
1246                             bool* is_binlog_active= NULL);
1247   /*
1248     init_show_field_list() prepares the column names and types for the
1249     output of SHOW BINLOG EVENTS; it is used only by SHOW BINLOG
1250     EVENTS.
1251   */
1252   static void init_show_field_list(List<Item>* field_list);
1253 #ifdef HAVE_REPLICATION
1254   int net_send(Protocol *protocol, const char* log_name, my_off_t pos);
1255 
1256   /**
1257     Stores a string representation of this event in the Protocol.
1258     This is used by SHOW BINLOG EVENTS.
1259 
1260     @retval 0 success
1261     @retval nonzero error
1262   */
1263   virtual int pack_info(Protocol *protocol);
1264 
1265 #endif /* HAVE_REPLICATION */
get_db()1266   virtual const char* get_db()
1267   {
1268     return thd ? thd->db : 0;
1269   }
1270 #else // ifdef MYSQL_SERVER
1271   Log_event(enum_event_cache_type cache_type_arg= EVENT_INVALID_CACHE,
1272             enum_event_logging_type logging_type_arg= EVENT_INVALID_LOGGING)
1273   : temp_buf(0), flags(0), event_cache_type(cache_type_arg),
1274     event_logging_type(logging_type_arg)
1275   { }
1276     /* avoid having to link mysqlbinlog against libpthread */
1277   static Log_event* read_log_event(IO_CACHE* file,
1278                                    const Format_description_log_event
1279                                    *description_event, my_bool crc_check);
1280   /* print*() functions are used by mysqlbinlog */
1281   virtual void print(FILE* file, PRINT_EVENT_INFO* print_event_info) = 0;
1282   void print_timestamp(IO_CACHE* file, time_t* ts);
1283   void print_header(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info,
1284                     bool is_more);
1285   void print_base64(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info,
1286                     bool is_more);
1287 #endif // ifdef MYSQL_SERVER ... else
1288   /*
1289      The value is set by caller of FD constructor and
1290      Log_event::write_header() for the rest.
1291      In the FD case it's propagated into the last byte
1292      of post_header_len[] at FD::write().
1293      On the slave side the value is assigned from post_header_len[last]
1294      of the last seen FD event.
1295   */
1296   uint8 checksum_alg;
1297 
new(size_t size)1298   static void *operator new(size_t size)
1299   {
1300     return (void*) my_malloc((uint)size, MYF(MY_WME|MY_FAE));
1301   }
1302 
delete(void * ptr,size_t)1303   static void operator delete(void *ptr, size_t)
1304   {
1305     my_free(ptr);
1306   }
1307 
1308   /* Placement version of the above operators */
new(size_t,void * ptr)1309   static void *operator new(size_t, void* ptr) { return ptr; }
delete(void *,void *)1310   static void operator delete(void*, void*) { }
1311   bool wrapper_my_b_safe_write(IO_CACHE* file, const uchar* buf, ulong data_length);
1312 
1313 #ifdef MYSQL_SERVER
1314   bool write_header(IO_CACHE* file, ulong data_length);
1315   bool write_footer(IO_CACHE* file);
1316   my_bool need_checksum();
1317 
write(IO_CACHE * file)1318   virtual bool write(IO_CACHE* file)
1319   {
1320     return(write_header(file, get_data_size()) ||
1321 	   write_data_header(file) ||
1322 	   write_data_body(file) ||
1323 	   write_footer(file));
1324   }
write_data_header(IO_CACHE * file)1325   virtual bool write_data_header(IO_CACHE* file)
1326   { return 0; }
write_data_body(IO_CACHE * file MY_ATTRIBUTE ((unused)))1327   virtual bool write_data_body(IO_CACHE* file MY_ATTRIBUTE((unused)))
1328   { return 0; }
get_time()1329   inline time_t get_time()
1330   {
1331     if (!when.tv_sec && !when.tv_usec) /* Not previously initialized */
1332     {
1333       THD *tmp_thd= thd ? thd : current_thd;
1334       if (tmp_thd)
1335         when= tmp_thd->start_time;
1336       else
1337         my_micro_time_to_timeval(my_micro_time(), &when);
1338     }
1339     return (time_t) when.tv_sec;
1340   }
1341 #endif
1342   virtual Log_event_type get_type_code() = 0;
1343   virtual bool is_valid() const = 0;
set_artificial_event()1344   void set_artificial_event() { flags |= LOG_EVENT_ARTIFICIAL_F; }
set_relay_log_event()1345   void set_relay_log_event() { flags |= LOG_EVENT_RELAY_LOG_F; }
is_artificial_event()1346   bool is_artificial_event() const { return flags & LOG_EVENT_ARTIFICIAL_F; }
is_relay_log_event()1347   bool is_relay_log_event() const { return flags & LOG_EVENT_RELAY_LOG_F; }
is_ignorable_event()1348   bool is_ignorable_event() const { return flags & LOG_EVENT_IGNORABLE_F; }
is_no_filter_event()1349   bool is_no_filter_event() const { return flags & LOG_EVENT_NO_FILTER_F; }
is_using_trans_cache()1350   inline bool is_using_trans_cache() const
1351   {
1352     return (event_cache_type == EVENT_TRANSACTIONAL_CACHE);
1353   }
is_using_stmt_cache()1354   inline bool is_using_stmt_cache() const
1355   {
1356     return(event_cache_type == EVENT_STMT_CACHE);
1357   }
is_using_immediate_logging()1358   inline bool is_using_immediate_logging() const
1359   {
1360     return(event_logging_type == EVENT_IMMEDIATE_LOGGING);
1361   }
1362   Log_event(const char* buf, const Format_description_log_event
1363             *description_event);
~Log_event()1364   virtual ~Log_event() { free_temp_buf();}
register_temp_buf(char * buf)1365   void register_temp_buf(char* buf) { temp_buf = buf; }
free_temp_buf()1366   void free_temp_buf()
1367   {
1368     if (temp_buf)
1369     {
1370       my_free(temp_buf);
1371       temp_buf = 0;
1372     }
1373   }
1374   /*
1375     Get event length for simple events. For complicated events the length
1376     is calculated during write()
1377   */
get_data_size()1378   virtual int get_data_size() { return 0;}
1379   static Log_event* read_log_event(const char* buf, uint event_len,
1380 				   const char **error,
1381                                    const Format_description_log_event
1382                                    *description_event, my_bool crc_check);
1383   /**
1384     Returns the human readable name of the given event type.
1385   */
1386   static const char* get_type_str(Log_event_type type);
1387   /**
1388     Returns the human readable name of this event's type.
1389   */
1390   const char* get_type_str();
1391 
1392   /* Return start of query time or current time */
1393 
1394 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
1395 
1396 private:
1397 
1398   /*
1399     possible decisions by get_mts_execution_mode().
1400     The execution mode can be PARALLEL or not (thereby sequential
1401     unless impossible at all). When it's sequential it further  breaks into
1402     ASYNChronous and SYNChronous.
1403   */
1404   enum enum_mts_event_exec_mode
1405   {
1406     /*
1407       Event is run by a Worker.
1408     */
1409     EVENT_EXEC_PARALLEL,
1410     /*
1411       Event is run by Coordinator.
1412     */
1413     EVENT_EXEC_ASYNC,
1414     /*
1415       Event is run by Coordinator and requires synchronization with Workers.
1416     */
1417     EVENT_EXEC_SYNC,
1418     /*
1419       Event can't be executed neither by Workers nor Coordinator.
1420     */
1421     EVENT_EXEC_CAN_NOT
1422   };
1423 
1424   /**
1425      Is called from get_mts_execution_mode() to
1426 
1427      @return TRUE  if the event needs applying with synchronization
1428                    agaist Workers, otherwise
1429              FALSE
1430 
1431      @note There are incompatile combinations such as referred further events
1432            are wrapped with BEGIN/COMMIT. Such cases should be identified
1433            by the caller and treats correspondingly.
1434 
1435            todo: to mts-support Old master Load-data related events
1436   */
is_mts_sequential_exec()1437   bool is_mts_sequential_exec()
1438   {
1439     return
1440       get_type_code() == START_EVENT_V3          ||
1441       get_type_code() == STOP_EVENT              ||
1442       get_type_code() == ROTATE_EVENT            ||
1443       get_type_code() == LOAD_EVENT              ||
1444       get_type_code() == SLAVE_EVENT             ||
1445       get_type_code() == CREATE_FILE_EVENT       ||
1446       get_type_code() == DELETE_FILE_EVENT       ||
1447       get_type_code() == NEW_LOAD_EVENT          ||
1448       get_type_code() == EXEC_LOAD_EVENT         ||
1449       get_type_code() == FORMAT_DESCRIPTION_EVENT||
1450 
1451       get_type_code() == INCIDENT_EVENT;
1452   }
1453 
1454   /**
1455      MTS Coordinator finds out a way how to execute the current event.
1456 
1457      Besides the parallelizable case, some events have to be applied by
1458      Coordinator concurrently with Workers and some to require synchronization
1459      with Workers (@c see wait_for_workers_to_finish) before to apply them.
1460 
1461      @retval EVENT_EXEC_PARALLEL  if event is executed by a Worker
1462      @retval EVENT_EXEC_ASYNC     if event is executed by Coordinator
1463      @retval EVENT_EXEC_SYNC      if event is executed by Coordinator
1464                                   with synchronization against the Workers
1465   */
get_mts_execution_mode(ulong slave_server_id,bool mts_in_group)1466   enum enum_mts_event_exec_mode get_mts_execution_mode(ulong slave_server_id,
1467                                                    bool mts_in_group)
1468   {
1469     if ((get_type_code() == FORMAT_DESCRIPTION_EVENT &&
1470          ((server_id == (uint32) ::server_id) || (log_pos == 0))) ||
1471         (get_type_code() == ROTATE_EVENT &&
1472          ((server_id == (uint32) ::server_id) ||
1473           (log_pos == 0    /* very first fake Rotate (R_f) */
1474            && mts_in_group /* ignored event turned into R_f at slave stop */))))
1475       return EVENT_EXEC_ASYNC;
1476     else if (is_mts_sequential_exec())
1477       return EVENT_EXEC_SYNC;
1478     else
1479       return EVENT_EXEC_PARALLEL;
1480   }
1481 
1482   /**
1483      @return index  in \in [0, M] range to indicate
1484              to be assigned worker;
1485              M is the max index of the worker pool.
1486   */
1487   Slave_worker *get_slave_worker(Relay_log_info *rli);
1488 
1489   /**
1490      The method fills in pointers to event's database name c-strings
1491      to a supplied array.
1492      In other than Query-log-event case the returned array contains
1493      just one item.
1494      @param[out] arg pointer to a struct containing char* array
1495                      pointers to be filled in and the number
1496                      of filled instances.
1497 
1498      @return     number of the filled intances indicating how many
1499                  databases the event accesses.
1500   */
get_mts_dbs(Mts_db_names * arg)1501   virtual uint8 get_mts_dbs(Mts_db_names *arg)
1502   {
1503     arg->name[0]= get_db();
1504 
1505     return arg->num= mts_number_dbs();
1506   }
1507 
1508   /*
1509     Group of events can be marked to force its execution
1510     in isolation from any other Workers.
1511     Typically that is done for a transaction that contains
1512     a query accessing more than OVER_MAX_DBS_IN_EVENT_MTS databases.
1513     Factually that's a sequential mode where a Worker remains to
1514     be the applier.
1515   */
set_mts_isolate_group()1516   virtual void set_mts_isolate_group()
1517   {
1518     DBUG_ASSERT(ends_group() ||
1519                 get_type_code() == QUERY_EVENT ||
1520                 get_type_code() == EXEC_LOAD_EVENT ||
1521                 get_type_code() == EXECUTE_LOAD_QUERY_EVENT);
1522     flags |= LOG_EVENT_MTS_ISOLATE_F;
1523   }
1524 
1525 
1526 public:
1527 
1528   /**
1529      @return TRUE  if events carries partitioning data (database names).
1530   */
1531   bool contains_partition_info(bool);
1532 
1533   /*
1534     @return  the number of updated by the event databases.
1535 
1536     @note In other than Query-log-event case that's one.
1537   */
mts_number_dbs()1538   virtual uint8 mts_number_dbs() { return 1; }
1539 
1540   /**
1541     @return TRUE  if the terminal event of a group is marked to
1542                   execute in isolation from other Workers,
1543             FASE  otherwise
1544   */
is_mts_group_isolated()1545   bool is_mts_group_isolated() { return flags & LOG_EVENT_MTS_ISOLATE_F; }
1546 
1547   /**
1548      Events of a certain type can start or end a group of events treated
1549      transactionally wrt binlog.
1550 
1551      Public access is required by implementation of recovery + skip.
1552 
1553      @return TRUE  if the event starts a group (transaction)
1554              FASE  otherwise
1555   */
starts_group()1556   virtual bool starts_group() { return FALSE; }
1557 
1558   /**
1559      @return TRUE  if the event ends a group (transaction)
1560              FASE  otherwise
1561   */
ends_group()1562   virtual bool ends_group()   { return FALSE; }
1563 
1564   /**
1565      Apply the event to the database.
1566 
1567      This function represents the public interface for applying an
1568      event.
1569 
1570      @see do_apply_event
1571    */
1572   int apply_event(Relay_log_info *rli);
1573 
1574   /**
1575      Update the relay log position.
1576 
1577      This function represents the public interface for "stepping over"
1578      the event and will update the relay log information.
1579 
1580      @see do_update_pos
1581    */
update_pos(Relay_log_info * rli)1582   int update_pos(Relay_log_info *rli)
1583   {
1584     return do_update_pos(rli);
1585   }
1586 
1587   /**
1588      Decide if the event shall be skipped, and the reason for skipping
1589      it.
1590 
1591      @see do_shall_skip
1592    */
shall_skip(Relay_log_info * rli)1593   enum_skip_reason shall_skip(Relay_log_info *rli)
1594   {
1595     return do_shall_skip(rli);
1596   }
1597 
1598   /**
1599     Primitive to apply an event to the database.
1600 
1601     This is where the change to the database is made.
1602 
1603     @note The primitive is protected instead of private, since there
1604     is a hierarchy of actions to be performed in some cases.
1605 
1606     @see Format_description_log_event::do_apply_event()
1607 
1608     @param rli Pointer to relay log info structure
1609 
1610     @retval 0     Event applied successfully
1611     @retval errno Error code if event application failed
1612   */
do_apply_event(Relay_log_info const * rli)1613   virtual int do_apply_event(Relay_log_info const *rli)
1614   {
1615     return 0;                /* Default implementation does nothing */
1616   }
1617 
1618   virtual int do_apply_event_worker(Slave_worker *w);
1619 
1620 protected:
1621 
1622   /**
1623      Helper function to ignore an event w.r.t. the slave skip counter.
1624 
1625      This function can be used inside do_shall_skip() for functions
1626      that cannot end a group. If the slave skip counter is 1 when
1627      seeing such an event, the event shall be ignored, the counter
1628      left intact, and processing continue with the next event.
1629 
1630      A typical usage is:
1631      @code
1632      enum_skip_reason do_shall_skip(Relay_log_info *rli) {
1633        return continue_group(rli);
1634      }
1635      @endcode
1636 
1637      @return Skip reason
1638    */
1639   enum_skip_reason continue_group(Relay_log_info *rli);
1640 
1641   /**
1642      Advance relay log coordinates.
1643 
1644      This function is called to advance the relay log coordinates to
1645      just after the event.  It is essential that both the relay log
1646      coordinate and the group log position is updated correctly, since
1647      this function is used also for skipping events.
1648 
1649      Normally, each implementation of do_update_pos() shall:
1650 
1651      - Update the event position to refer to the position just after
1652        the event.
1653 
1654      - Update the group log position to refer to the position just
1655        after the event <em>if the event is last in a group</em>
1656 
1657      @param rli Pointer to relay log info structure
1658 
1659      @retval 0     Coordinates changed successfully
1660      @retval errno Error code if advancing failed (usually just
1661                    1). Observe that handler errors are returned by the
1662                    do_apply_event() function, and not by this one.
1663    */
1664   virtual int do_update_pos(Relay_log_info *rli);
1665 
1666 
1667   /**
1668      Decide if this event shall be skipped or not and the reason for
1669      skipping it.
1670 
1671      The default implementation decide that the event shall be skipped
1672      if either:
1673 
1674      - the server id of the event is the same as the server id of the
1675        server and <code>rli->replicate_same_server_id</code> is true,
1676        or
1677 
1678      - if <code>rli->slave_skip_counter</code> is greater than zero.
1679 
1680      @see do_apply_event
1681      @see do_update_pos
1682 
1683      @retval Log_event::EVENT_SKIP_NOT
1684      The event shall not be skipped and should be applied.
1685 
1686      @retval Log_event::EVENT_SKIP_IGNORE
1687      The event shall be skipped by just ignoring it, i.e., the slave
1688      skip counter shall not be changed. This happends if, for example,
1689      the originating server id of the event is the same as the server
1690      id of the slave.
1691 
1692      @retval Log_event::EVENT_SKIP_COUNT
1693      The event shall be skipped because the slave skip counter was
1694      non-zero. The caller shall decrease the counter by one.
1695    */
1696   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
1697 #endif
1698 };
1699 
1700 
1701 /*
1702    One class for each type of event.
1703    Two constructors for each class:
1704    - one to create the event for logging (when the server acts as a master),
1705    called after an update to the database is done,
1706    which accepts parameters like the query, the database, the options for LOAD
1707    DATA INFILE...
1708    - one to create the event from a packet (when the server acts as a slave),
1709    called before reproducing the update, which accepts parameters (like a
1710    buffer). Used to read from the master, from the relay log, and in
1711    mysqlbinlog. This constructor must be format-tolerant.
1712 */
1713 
1714 /**
1715   @class Query_log_event
1716 
1717   A @c Query_log_event is created for each query that modifies the
1718   database, unless the query is logged row-based.
1719 
1720   @section Query_log_event_binary_format Binary format
1721 
1722   See @ref Log_event_binary_format "Binary format for log events" for
1723   a general discussion and introduction to the binary format of binlog
1724   events.
1725 
1726   The Post-Header has five components:
1727 
1728   <table>
1729   <caption>Post-Header for Query_log_event</caption>
1730 
1731   <tr>
1732     <th>Name</th>
1733     <th>Format</th>
1734     <th>Description</th>
1735   </tr>
1736 
1737   <tr>
1738     <td>slave_proxy_id</td>
1739     <td>4 byte unsigned integer</td>
1740     <td>An integer identifying the client thread that issued the
1741     query.  The id is unique per server.  (Note, however, that two
1742     threads on different servers may have the same slave_proxy_id.)
1743     This is used when a client thread creates a temporary table local
1744     to the client.  The slave_proxy_id is used to distinguish
1745     temporary tables that belong to different clients.
1746     </td>
1747   </tr>
1748 
1749   <tr>
1750     <td>exec_time</td>
1751     <td>4 byte unsigned integer</td>
1752     <td>The time from when the query started to when it was logged in
1753     the binlog, in seconds.</td>
1754   </tr>
1755 
1756   <tr>
1757     <td>db_len</td>
1758     <td>1 byte integer</td>
1759     <td>The length of the name of the currently selected database.</td>
1760   </tr>
1761 
1762   <tr>
1763     <td>error_code</td>
1764     <td>2 byte unsigned integer</td>
1765     <td>Error code generated by the master.  If the master fails, the
1766     slave will fail with the same error code, except for the error
1767     codes ER_DB_CREATE_EXISTS == 1007 and ER_DB_DROP_EXISTS == 1008.
1768     </td>
1769   </tr>
1770 
1771   <tr>
1772     <td>status_vars_len</td>
1773     <td>2 byte unsigned integer</td>
1774     <td>The length of the status_vars block of the Body, in bytes. See
1775     @ref query_log_event_status_vars "below".
1776     </td>
1777   </tr>
1778   </table>
1779 
1780   The Body has the following components:
1781 
1782   <table>
1783   <caption>Body for Query_log_event</caption>
1784 
1785   <tr>
1786     <th>Name</th>
1787     <th>Format</th>
1788     <th>Description</th>
1789   </tr>
1790 
1791   <tr>
1792     <td>@anchor query_log_event_status_vars status_vars</td>
1793     <td>status_vars_len bytes</td>
1794     <td>Zero or more status variables.  Each status variable consists
1795     of one byte identifying the variable stored, followed by the value
1796     of the variable.  The possible variables are listed separately in
1797     the table @ref Table_query_log_event_status_vars "below".  MySQL
1798     always writes events in the order defined below; however, it is
1799     capable of reading them in any order.  </td>
1800   </tr>
1801 
1802   <tr>
1803     <td>db</td>
1804     <td>db_len+1</td>
1805     <td>The currently selected database, as a null-terminated string.
1806 
1807     (The trailing zero is redundant since the length is already known;
1808     it is db_len from Post-Header.)
1809     </td>
1810   </tr>
1811 
1812   <tr>
1813     <td>query</td>
1814     <td>variable length string without trailing zero, extending to the
1815     end of the event (determined by the length field of the
1816     Common-Header)
1817     </td>
1818     <td>The SQL query.</td>
1819   </tr>
1820   </table>
1821 
1822   The following table lists the status variables that may appear in
1823   the status_vars field.
1824 
1825   @anchor Table_query_log_event_status_vars
1826   <table>
1827   <caption>Status variables for Query_log_event</caption>
1828 
1829   <tr>
1830     <th>Status variable</th>
1831     <th>1 byte identifier</th>
1832     <th>Format</th>
1833     <th>Description</th>
1834   </tr>
1835 
1836   <tr>
1837     <td>flags2</td>
1838     <td>Q_FLAGS2_CODE == 0</td>
1839     <td>4 byte bitfield</td>
1840     <td>The flags in @c thd->options, binary AND-ed with @c
1841     OPTIONS_WRITTEN_TO_BIN_LOG.  The @c thd->options bitfield contains
1842     options for "SELECT".  @c OPTIONS_WRITTEN identifies those options
1843     that need to be written to the binlog (not all do).  Specifically,
1844     @c OPTIONS_WRITTEN_TO_BIN_LOG equals (@c OPTION_AUTO_IS_NULL | @c
1845     OPTION_NO_FOREIGN_KEY_CHECKS | @c OPTION_RELAXED_UNIQUE_CHECKS |
1846     @c OPTION_NOT_AUTOCOMMIT), or 0x0c084000 in hex.
1847 
1848     These flags correspond to the SQL variables SQL_AUTO_IS_NULL,
1849     FOREIGN_KEY_CHECKS, UNIQUE_CHECKS, and AUTOCOMMIT, documented in
1850     the "SET Syntax" section of the MySQL Manual.
1851 
1852     This field is always written to the binlog in version >= 5.0, and
1853     never written in version < 5.0.
1854     </td>
1855   </tr>
1856 
1857   <tr>
1858     <td>sql_mode</td>
1859     <td>Q_SQL_MODE_CODE == 1</td>
1860     <td>8 byte bitfield</td>
1861     <td>The @c sql_mode variable.  See the section "SQL Modes" in the
1862     MySQL manual, and see sql_priv.h for a list of the possible
1863     flags. Currently (2007-10-04), the following flags are available:
1864     <pre>
1865     MODE_REAL_AS_FLOAT==0x1
1866     MODE_PIPES_AS_CONCAT==0x2
1867     MODE_ANSI_QUOTES==0x4
1868     MODE_IGNORE_SPACE==0x8
1869     MODE_NOT_USED==0x10
1870     MODE_ONLY_FULL_GROUP_BY==0x20
1871     MODE_NO_UNSIGNED_SUBTRACTION==0x40
1872     MODE_NO_DIR_IN_CREATE==0x80
1873     MODE_POSTGRESQL==0x100
1874     MODE_ORACLE==0x200
1875     MODE_MSSQL==0x400
1876     MODE_DB2==0x800
1877     MODE_MAXDB==0x1000
1878     MODE_NO_KEY_OPTIONS==0x2000
1879     MODE_NO_TABLE_OPTIONS==0x4000
1880     MODE_NO_FIELD_OPTIONS==0x8000
1881     MODE_MYSQL323==0x10000
1882     MODE_MYSQL323==0x20000
1883     MODE_MYSQL40==0x40000
1884     MODE_ANSI==0x80000
1885     MODE_NO_AUTO_VALUE_ON_ZERO==0x100000
1886     MODE_NO_BACKSLASH_ESCAPES==0x200000
1887     MODE_STRICT_TRANS_TABLES==0x400000
1888     MODE_STRICT_ALL_TABLES==0x800000
1889     MODE_NO_ZERO_IN_DATE==0x1000000
1890     MODE_NO_ZERO_DATE==0x2000000
1891     MODE_INVALID_DATES==0x4000000
1892     MODE_ERROR_FOR_DIVISION_BY_ZERO==0x8000000
1893     MODE_TRADITIONAL==0x10000000
1894     MODE_NO_AUTO_CREATE_USER==0x20000000
1895     MODE_HIGH_NOT_PRECEDENCE==0x40000000
1896     MODE_PAD_CHAR_TO_FULL_LENGTH==0x80000000
1897     </pre>
1898     All these flags are replicated from the server.  However, all
1899     flags except @c MODE_NO_DIR_IN_CREATE are honored by the slave;
1900     the slave always preserves its old value of @c
1901     MODE_NO_DIR_IN_CREATE.  For a rationale, see comment in
1902     @c Query_log_event::do_apply_event in @c log_event.cc.
1903 
1904     This field is always written to the binlog.
1905     </td>
1906   </tr>
1907 
1908   <tr>
1909     <td>catalog</td>
1910     <td>Q_CATALOG_NZ_CODE == 6</td>
1911     <td>Variable-length string: the length in bytes (1 byte) followed
1912     by the characters (at most 255 bytes)
1913     </td>
1914     <td>Stores the client's current catalog.  Every database belongs
1915     to a catalog, the same way that every table belongs to a
1916     database.  Currently, there is only one catalog, "std".
1917 
1918     This field is written if the length of the catalog is > 0;
1919     otherwise it is not written.
1920     </td>
1921   </tr>
1922 
1923   <tr>
1924     <td>auto_increment</td>
1925     <td>Q_AUTO_INCREMENT == 3</td>
1926     <td>two 2 byte unsigned integers, totally 2+2=4 bytes</td>
1927 
1928     <td>The two variables auto_increment_increment and
1929     auto_increment_offset, in that order.  For more information, see
1930     "System variables" in the MySQL manual.
1931 
1932     This field is written if auto_increment > 1.  Otherwise, it is not
1933     written.
1934     </td>
1935   </tr>
1936 
1937   <tr>
1938     <td>charset</td>
1939     <td>Q_CHARSET_CODE == 4</td>
1940     <td>three 2 byte unsigned integers, totally 2+2+2=6 bytes</td>
1941     <td>The three variables character_set_client,
1942     collation_connection, and collation_server, in that order.
1943     character_set_client is a code identifying the character set and
1944     collation used by the client to encode the query.
1945     collation_connection identifies the character set and collation
1946     that the master converts the query to when it receives it; this is
1947     useful when comparing literal strings.  collation_server is the
1948     default character set and collation used when a new database is
1949     created.
1950 
1951     See also "Connection Character Sets and Collations" in the MySQL
1952     5.1 manual.
1953 
1954     All three variables are codes identifying a (character set,
1955     collation) pair.  To see which codes map to which pairs, run the
1956     query "SELECT id, character_set_name, collation_name FROM
1957     COLLATIONS".
1958 
1959     Cf. Q_CHARSET_DATABASE_CODE below.
1960 
1961     This field is always written.
1962     </td>
1963   </tr>
1964 
1965   <tr>
1966     <td>time_zone</td>
1967     <td>Q_TIME_ZONE_CODE == 5</td>
1968     <td>Variable-length string: the length in bytes (1 byte) followed
1969     by the characters (at most 255 bytes).
1970     <td>The time_zone of the master.
1971 
1972     See also "System Variables" and "MySQL Server Time Zone Support"
1973     in the MySQL manual.
1974 
1975     This field is written if the length of the time zone string is >
1976     0; otherwise, it is not written.
1977     </td>
1978   </tr>
1979 
1980   <tr>
1981     <td>lc_time_names_number</td>
1982     <td>Q_LC_TIME_NAMES_CODE == 7</td>
1983     <td>2 byte integer</td>
1984     <td>A code identifying a table of month and day names.  The
1985     mapping from codes to languages is defined in @c sql_locale.cc.
1986 
1987     This field is written if it is not 0, i.e., if the locale is not
1988     en_US.
1989     </td>
1990   </tr>
1991 
1992   <tr>
1993     <td>charset_database_number</td>
1994     <td>Q_CHARSET_DATABASE_CODE == 8</td>
1995     <td>2 byte integer</td>
1996 
1997     <td>The value of the collation_database system variable (in the
1998     source code stored in @c thd->variables.collation_database), which
1999     holds the code for a (character set, collation) pair as described
2000     above (see Q_CHARSET_CODE).
2001 
2002     collation_database was used in old versions (???WHEN).  Its value
2003     was loaded when issuing a "use db" query and could be changed by
2004     issuing a "SET collation_database=xxx" query.  It used to affect
2005     the "LOAD DATA INFILE" and "CREATE TABLE" commands.
2006 
2007     In newer versions, "CREATE TABLE" has been changed to take the
2008     character set from the database of the created table, rather than
2009     the character set of the current database.  This makes a
2010     difference when creating a table in another database than the
2011     current one.  "LOAD DATA INFILE" has not yet changed to do this,
2012     but there are plans to eventually do it, and to make
2013     collation_database read-only.
2014 
2015     This field is written if it is not 0.
2016     </td>
2017   </tr>
2018   <tr>
2019     <td>table_map_for_update</td>
2020     <td>Q_TABLE_MAP_FOR_UPDATE_CODE == 9</td>
2021     <td>8 byte integer</td>
2022 
2023     <td>The value of the table map that is to be updated by the
2024     multi-table update query statement. Every bit of this variable
2025     represents a table, and is set to 1 if the corresponding table is
2026     to be updated by this statement.
2027 
2028     The value of this variable is set when executing a multi-table update
2029     statement and used by slave to apply filter rules without opening
2030     all the tables on slave. This is required because some tables may
2031     not exist on slave because of the filter rules.
2032     </td>
2033   </tr>
2034   </table>
2035 
2036   @subsection Query_log_event_notes_on_previous_versions Notes on Previous Versions
2037 
2038   * Status vars were introduced in version 5.0.  To read earlier
2039   versions correctly, check the length of the Post-Header.
2040 
2041   * The status variable Q_CATALOG_CODE == 2 existed in MySQL 5.0.x,
2042   where 0<=x<=3.  It was identical to Q_CATALOG_CODE, except that the
2043   string had a trailing '\0'.  The '\0' was removed in 5.0.4 since it
2044   was redundant (the string length is stored before the string).  The
2045   Q_CATALOG_CODE will never be written by a new master, but can still
2046   be understood by a new slave.
2047 
2048   * See Q_CHARSET_DATABASE_CODE in the table above.
2049 
2050   * When adding new status vars, please don't forget to update the
2051   MAX_SIZE_LOG_EVENT_STATUS, and update function code_name
2052 
2053 */
2054 class Query_log_event: public Log_event
2055 {
2056   LEX_STRING user;
2057   LEX_STRING host;
2058 protected:
2059   Log_event::Byte* data_buf;
2060 public:
2061   const char* query;
2062   const char* catalog;
2063   const char* db;
2064   /*
2065     If we already know the length of the query string
2066     we pass it with q_len, so we would not have to call strlen()
2067     otherwise, set it to 0, in which case, we compute it with strlen()
2068   */
2069   uint32 q_len;
2070   uint32 db_len;
2071   uint16 error_code;
2072   ulong thread_id;
2073   /*
2074     For events created by Query_log_event::do_apply_event (and
2075     Load_log_event::do_apply_event()) we need the *original* thread
2076     id, to be able to log the event with the original (=master's)
2077     thread id (fix for BUG#1686).
2078   */
2079   ulong slave_proxy_id;
2080 
2081   /*
2082     Binlog format 3 and 4 start to differ (as far as class members are
2083     concerned) from here.
2084   */
2085 
2086   uint catalog_len;			// <= 255 char; 0 means uninited
2087 
2088   /*
2089     We want to be able to store a variable number of N-bit status vars:
2090     (generally N=32; but N=64 for SQL_MODE) a user may want to log the number
2091     of affected rows (for debugging) while another does not want to lose 4
2092     bytes in this.
2093     The storage on disk is the following:
2094     status_vars_len is part of the post-header,
2095     status_vars are in the variable-length part, after the post-header, before
2096     the db & query.
2097     status_vars on disk is a sequence of pairs (code, value) where 'code' means
2098     'sql_mode', 'affected' etc. Sometimes 'value' must be a short string, so
2099     its first byte is its length. For now the order of status vars is:
2100     flags2 - sql_mode - catalog - autoinc - charset
2101     We should add the same thing to Load_log_event, but in fact
2102     LOAD DATA INFILE is going to be logged with a new type of event (logging of
2103     the plain text query), so Load_log_event would be frozen, so no need. The
2104     new way of logging LOAD DATA INFILE would use a derived class of
2105     Query_log_event, so automatically benefit from the work already done for
2106     status variables in Query_log_event.
2107  */
2108   uint16 status_vars_len;
2109 
2110   /*
2111     'flags2' is a second set of flags (on top of those in Log_event), for
2112     session variables. These are thd->options which is & against a mask
2113     (OPTIONS_WRITTEN_TO_BIN_LOG).
2114     flags2_inited helps make a difference between flags2==0 (3.23 or 4.x
2115     master, we don't know flags2, so use the slave server's global options) and
2116     flags2==0 (5.0 master, we know this has a meaning of flags all down which
2117     must influence the query).
2118   */
2119   bool flags2_inited;
2120   bool sql_mode_inited;
2121   bool charset_inited;
2122 
2123   uint32 flags2;
2124   /* In connections sql_mode is 32 bits now but will be 64 bits soon */
2125   sql_mode_t sql_mode;
2126   ulong auto_increment_increment, auto_increment_offset;
2127   char charset[6];
2128   uint time_zone_len; /* 0 means uninited */
2129   const char *time_zone_str;
2130   uint lc_time_names_number; /* 0 means en_US */
2131   uint charset_database_number;
2132   /*
2133     map for tables that will be updated for a multi-table update query
2134     statement, for other query statements, this will be zero.
2135   */
2136   ulonglong table_map_for_update;
2137   /*
2138     Holds the original length of a Query_log_event that comes from a
2139     master of version < 5.0 (i.e., binlog_version < 4). When the IO
2140     thread writes the relay log, it augments the Query_log_event with a
2141     Q_MASTER_DATA_WRITTEN_CODE status_var that holds the original event
2142     length. This field is initialized to non-zero in the SQL thread when
2143     it reads this augmented event. SQL thread does not write
2144     Q_MASTER_DATA_WRITTEN_CODE to the slave's server binlog.
2145   */
2146   uint32 master_data_written;
2147   /*
2148     number of updated databases by the query and their names. This info
2149     is requested by both Coordinator and Worker.
2150   */
2151   uchar mts_accessed_dbs;
2152   char mts_accessed_db_names[MAX_DBS_IN_EVENT_MTS][NAME_LEN];
2153 
2154 #ifdef MYSQL_SERVER
2155 
2156   Query_log_event(THD* thd_arg, const char* query_arg, ulong query_length,
2157                   bool using_trans, bool immediate, bool suppress_use,
2158                   int error, bool ignore_command= FALSE);
get_db()2159   const char* get_db() { return db; }
2160 
2161   /**
2162      @param[out] arg pointer to a struct containing char* array
2163                      pointers be filled in and the number of
2164                      filled instances.
2165                      In case the number exceeds MAX_DBS_IN_EVENT_MTS,
2166                      the overfill is indicated with assigning the number to
2167                      OVER_MAX_DBS_IN_EVENT_MTS.
2168 
2169      @return     number of databases in the array or OVER_MAX_DBS_IN_EVENT_MTS.
2170   */
get_mts_dbs(Mts_db_names * arg)2171   virtual uint8 get_mts_dbs(Mts_db_names* arg)
2172   {
2173     if (mts_accessed_dbs == OVER_MAX_DBS_IN_EVENT_MTS)
2174     {
2175       // the empty string db name is special to indicate sequential applying
2176       mts_accessed_db_names[0][0]= 0;
2177     }
2178     else
2179     {
2180       for (uchar i= 0; i < mts_accessed_dbs; i++)
2181       {
2182         char *db_name= mts_accessed_db_names[i];
2183 
2184         // Only default database is rewritten.
2185         if (!rpl_filter->is_rewrite_empty() && !strcmp(get_db(), db_name))
2186         {
2187           size_t dummy_len;
2188           const char *db_filtered= rpl_filter->get_rewrite_db(db_name, &dummy_len);
2189           // db_name != db_filtered means that db_name is rewritten.
2190           if (strcmp(db_name, db_filtered))
2191             db_name= (char*)db_filtered;
2192         }
2193         arg->name[i]= db_name;
2194       }
2195     }
2196     return arg->num= mts_accessed_dbs;
2197   }
2198 
2199   void attach_temp_tables_worker(THD*);
2200   void detach_temp_tables_worker(THD*);
2201 
mts_number_dbs()2202   virtual uchar mts_number_dbs() { return mts_accessed_dbs; }
2203 
2204 #ifdef HAVE_REPLICATION
2205   int pack_info(Protocol* protocol);
2206 #endif /* HAVE_REPLICATION */
2207 #else
2208   void print_query_header(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info);
2209   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
2210 #endif
2211 
2212   Query_log_event();
2213   Query_log_event(const char* buf, uint event_len,
2214                   const Format_description_log_event *description_event,
2215                   Log_event_type event_type);
~Query_log_event()2216   ~Query_log_event()
2217   {
2218     if (data_buf)
2219       my_free(data_buf);
2220   }
get_type_code()2221   Log_event_type get_type_code() { return QUERY_EVENT; }
2222 #ifdef MYSQL_SERVER
2223   bool write(IO_CACHE* file);
write_post_header_for_derived(IO_CACHE * file)2224   virtual bool write_post_header_for_derived(IO_CACHE* file) { return FALSE; }
2225 #endif
is_valid()2226   bool is_valid() const { return query != 0; }
2227 
2228   /*
2229     Returns number of bytes additionaly written to post header by derived
2230     events (so far it is only Execute_load_query event).
2231   */
get_post_header_size_for_derived()2232   virtual ulong get_post_header_size_for_derived() { return 0; }
2233   /* Writes derived event-specific part of post header. */
2234 
2235 public:        /* !!! Public in this patch to allow old usage */
2236 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
2237   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
2238   virtual int do_apply_event(Relay_log_info const *rli);
2239   virtual int do_update_pos(Relay_log_info *rli);
2240 
2241   int do_apply_event(Relay_log_info const *rli,
2242                        const char *query_arg,
2243                        uint32 q_len_arg);
2244 #endif /* HAVE_REPLICATION */
2245   /*
2246     If true, the event always be applied by slave SQL thread or be printed by
2247     mysqlbinlog
2248    */
is_trans_keyword()2249   bool is_trans_keyword()
2250   {
2251     /*
2252       Before the patch for bug#50407, The 'SAVEPOINT and ROLLBACK TO'
2253       queries input by user was written into log events directly.
2254       So the keywords can be written in both upper case and lower case
2255       together, strncasecmp is used to check both cases. they also could be
2256       binlogged with comments in the front of these keywords. for examples:
2257         / * bla bla * / SAVEPOINT a;
2258         / * bla bla * / ROLLBACK TO a;
2259       but we don't handle these cases and after the patch, both quiries are
2260       binlogged in upper case with no comments.
2261      */
2262     return !strncmp(query, "BEGIN", q_len) ||
2263       !strncmp(query, "COMMIT", q_len) ||
2264       !strncasecmp(query, "SAVEPOINT", 9) ||
2265       !strncasecmp(query, "ROLLBACK", 8);
2266   }
2267   /**
2268      Notice, DDL queries are logged without BEGIN/COMMIT parentheses
2269      and identification of such single-query group
2270      occures within logics of @c get_slave_worker().
2271   */
starts_group()2272   bool starts_group() { return !strncmp(query, "BEGIN", q_len); }
ends_group()2273   virtual bool ends_group()
2274   {
2275     return
2276       !strncmp(query, "COMMIT", q_len) ||
2277       (!strncasecmp(query, STRING_WITH_LEN("ROLLBACK"))
2278        && strncasecmp(query, STRING_WITH_LEN("ROLLBACK TO ")));
2279   }
2280 };
2281 
2282 
2283 /**
2284   @class Load_log_event
2285 
2286   This log event corresponds to a "LOAD DATA INFILE" SQL query on the
2287   following form:
2288 
2289   @verbatim
2290    (1)    USE db;
2291    (2)    LOAD DATA [CONCURRENT] [LOCAL] INFILE 'file_name'
2292    (3)    [REPLACE | IGNORE]
2293    (4)    INTO TABLE 'table_name'
2294    (5)    [FIELDS
2295    (6)      [TERMINATED BY 'field_term']
2296    (7)      [[OPTIONALLY] ENCLOSED BY 'enclosed']
2297    (8)      [ESCAPED BY 'escaped']
2298    (9)    ]
2299   (10)    [LINES
2300   (11)      [TERMINATED BY 'line_term']
2301   (12)      [LINES STARTING BY 'line_start']
2302   (13)    ]
2303   (14)    [IGNORE skip_lines LINES]
2304   (15)    (field_1, field_2, ..., field_n)@endverbatim
2305 
2306   @section Load_log_event_binary_format Binary Format
2307 
2308   The Post-Header consists of the following six components.
2309 
2310   <table>
2311   <caption>Post-Header for Load_log_event</caption>
2312 
2313   <tr>
2314     <th>Name</th>
2315     <th>Format</th>
2316     <th>Description</th>
2317   </tr>
2318 
2319   <tr>
2320     <td>slave_proxy_id</td>
2321     <td>4 byte unsigned integer</td>
2322     <td>An integer identifying the client thread that issued the
2323     query.  The id is unique per server.  (Note, however, that two
2324     threads on different servers may have the same slave_proxy_id.)
2325     This is used when a client thread creates a temporary table local
2326     to the client.  The slave_proxy_id is used to distinguish
2327     temporary tables that belong to different clients.
2328     </td>
2329   </tr>
2330 
2331   <tr>
2332     <td>exec_time</td>
2333     <td>4 byte unsigned integer</td>
2334     <td>The time from when the query started to when it was logged in
2335     the binlog, in seconds.</td>
2336   </tr>
2337 
2338   <tr>
2339     <td>skip_lines</td>
2340     <td>4 byte unsigned integer</td>
2341     <td>The number on line (14) above, if present, or 0 if line (14)
2342     is left out.
2343     </td>
2344   </tr>
2345 
2346   <tr>
2347     <td>table_name_len</td>
2348     <td>1 byte unsigned integer</td>
2349     <td>The length of 'table_name' on line (4) above.</td>
2350   </tr>
2351 
2352   <tr>
2353     <td>db_len</td>
2354     <td>1 byte unsigned integer</td>
2355     <td>The length of 'db' on line (1) above.</td>
2356   </tr>
2357 
2358   <tr>
2359     <td>num_fields</td>
2360     <td>4 byte unsigned integer</td>
2361     <td>The number n of fields on line (15) above.</td>
2362   </tr>
2363   </table>
2364 
2365   The Body contains the following components.
2366 
2367   <table>
2368   <caption>Body of Load_log_event</caption>
2369 
2370   <tr>
2371     <th>Name</th>
2372     <th>Format</th>
2373     <th>Description</th>
2374   </tr>
2375 
2376   <tr>
2377     <td>sql_ex</td>
2378     <td>variable length</td>
2379 
2380     <td>Describes the part of the query on lines (3) and
2381     (5)&ndash;(13) above.  More precisely, it stores the five strings
2382     (on lines) field_term (6), enclosed (7), escaped (8), line_term
2383     (11), and line_start (12); as well as a bitfield indicating the
2384     presence of the keywords REPLACE (3), IGNORE (3), and OPTIONALLY
2385     (7).
2386 
2387     The data is stored in one of two formats, called "old" and "new".
2388     The type field of Common-Header determines which of these two
2389     formats is used: type LOAD_EVENT means that the old format is
2390     used, and type NEW_LOAD_EVENT means that the new format is used.
2391     When MySQL writes a Load_log_event, it uses the new format if at
2392     least one of the five strings is two or more bytes long.
2393     Otherwise (i.e., if all strings are 0 or 1 bytes long), the old
2394     format is used.
2395 
2396     The new and old format differ in the way the five strings are
2397     stored.
2398 
2399     <ul>
2400     <li> In the new format, the strings are stored in the order
2401     field_term, enclosed, escaped, line_term, line_start. Each string
2402     consists of a length (1 byte), followed by a sequence of
2403     characters (0-255 bytes).  Finally, a boolean combination of the
2404     following flags is stored in 1 byte: REPLACE_FLAG==0x4,
2405     IGNORE_FLAG==0x8, and OPT_ENCLOSED_FLAG==0x2.  If a flag is set,
2406     it indicates the presence of the corresponding keyword in the SQL
2407     query.
2408 
2409     <li> In the old format, we know that each string has length 0 or
2410     1.  Therefore, only the first byte of each string is stored.  The
2411     order of the strings is the same as in the new format.  These five
2412     bytes are followed by the same 1 byte bitfield as in the new
2413     format.  Finally, a 1 byte bitfield called empty_flags is stored.
2414     The low 5 bits of empty_flags indicate which of the five strings
2415     have length 0.  For each of the following flags that is set, the
2416     corresponding string has length 0; for the flags that are not set,
2417     the string has length 1: FIELD_TERM_EMPTY==0x1,
2418     ENCLOSED_EMPTY==0x2, LINE_TERM_EMPTY==0x4, LINE_START_EMPTY==0x8,
2419     ESCAPED_EMPTY==0x10.
2420     </ul>
2421 
2422     Thus, the size of the new format is 6 bytes + the sum of the sizes
2423     of the five strings.  The size of the old format is always 7
2424     bytes.
2425     </td>
2426   </tr>
2427 
2428   <tr>
2429     <td>field_lens</td>
2430     <td>num_fields 1 byte unsigned integers</td>
2431     <td>An array of num_fields integers representing the length of
2432     each field in the query.  (num_fields is from the Post-Header).
2433     </td>
2434   </tr>
2435 
2436   <tr>
2437     <td>fields</td>
2438     <td>num_fields null-terminated strings</td>
2439     <td>An array of num_fields null-terminated strings, each
2440     representing a field in the query.  (The trailing zero is
2441     redundant, since the length are stored in the num_fields array.)
2442     The total length of all strings equals to the sum of all
2443     field_lens, plus num_fields bytes for all the trailing zeros.
2444     </td>
2445   </tr>
2446 
2447   <tr>
2448     <td>table_name</td>
2449     <td>null-terminated string of length table_len+1 bytes</td>
2450     <td>The 'table_name' from the query, as a null-terminated string.
2451     (The trailing zero is actually redundant since the table_len is
2452     known from Post-Header.)
2453     </td>
2454   </tr>
2455 
2456   <tr>
2457     <td>db</td>
2458     <td>null-terminated string of length db_len+1 bytes</td>
2459     <td>The 'db' from the query, as a null-terminated string.
2460     (The trailing zero is actually redundant since the db_len is known
2461     from Post-Header.)
2462     </td>
2463   </tr>
2464 
2465   <tr>
2466     <td>file_name</td>
2467     <td>variable length string without trailing zero, extending to the
2468     end of the event (determined by the length field of the
2469     Common-Header)
2470     </td>
2471     <td>The 'file_name' from the query.
2472     </td>
2473   </tr>
2474 
2475   </table>
2476 
2477   @subsection Load_log_event_notes_on_previous_versions Notes on Previous Versions
2478 
2479   This event type is understood by current versions, but only
2480   generated by MySQL 3.23 and earlier.
2481 */
2482 class Load_log_event: public Log_event
2483 {
2484 private:
2485 protected:
2486   int copy_log_event(const char *buf, ulong event_len,
2487                      int body_offset,
2488                      const Format_description_log_event* description_event);
2489 
2490 public:
2491   uint get_query_buffer_length();
2492   void print_query(bool need_db, const char *cs, char *buf, char **end,
2493                    char **fn_start, char **fn_end);
2494   ulong thread_id;
2495   ulong slave_proxy_id;
2496   uint32 table_name_len;
2497   /*
2498     No need to have a catalog, as these events can only come from 4.x.
2499     TODO: this may become false if Dmitri pushes his new LOAD DATA INFILE in
2500     5.0 only (not in 4.x).
2501   */
2502   uint32 db_len;
2503   uint32 fname_len;
2504   uint32 num_fields;
2505   const char* fields;
2506   const uchar* field_lens;
2507   uint32 field_block_len;
2508 
2509   const char* table_name;
2510   const char* db;
2511   const char* fname;
2512   uint32 skip_lines;
2513   sql_ex_info sql_ex;
2514   bool local_fname;
2515   /**
2516     Indicates that this event corresponds to LOAD DATA CONCURRENT,
2517 
2518     @note Since Load_log_event event coming from the binary log
2519           lacks information whether LOAD DATA on master was concurrent
2520           or not, this flag is only set to TRUE for an auxiliary
2521           Load_log_event object which is used in mysql_load() to
2522           re-construct LOAD DATA statement from function parameters,
2523           for logging.
2524   */
2525   bool is_concurrent;
2526 
2527   /* fname doesn't point to memory inside Log_event::temp_buf  */
set_fname_outside_temp_buf(const char * afname,uint alen)2528   void set_fname_outside_temp_buf(const char *afname, uint alen)
2529   {
2530     fname= afname;
2531     fname_len= alen;
2532     local_fname= TRUE;
2533   }
2534   /* fname doesn't point to memory inside Log_event::temp_buf  */
check_fname_outside_temp_buf()2535   int  check_fname_outside_temp_buf()
2536   {
2537     return local_fname;
2538   }
2539 
2540 #ifdef MYSQL_SERVER
2541   String field_lens_buf;
2542   String fields_buf;
2543 
2544   Load_log_event(THD* thd, sql_exchange* ex, const char* db_arg,
2545 		 const char* table_name_arg,
2546 		 List<Item>& fields_arg,
2547                  bool is_concurrent_arg,
2548                  enum enum_duplicates handle_dup, bool ignore,
2549 		 bool using_trans);
2550   void set_fields(const char* db, List<Item> &fields_arg,
2551                   Name_resolution_context *context);
get_db()2552   const char* get_db() { return db; }
2553 #ifdef HAVE_REPLICATION
2554   int pack_info(Protocol* protocol);
2555 #endif /* HAVE_REPLICATION */
2556 #else
2557   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
2558   void print(FILE* file, PRINT_EVENT_INFO* print_event_info, bool commented);
2559 #endif
2560 
2561   /*
2562     Note that for all the events related to LOAD DATA (Load_log_event,
2563     Create_file/Append/Exec/Delete, we pass description_event; however as
2564     logging of LOAD DATA is going to be changed in 4.1 or 5.0, this is only used
2565     for the common_header_len (post_header_len will not be changed).
2566   */
2567   Load_log_event(const char* buf, uint event_len,
2568                  const Format_description_log_event* description_event);
~Load_log_event()2569   ~Load_log_event()
2570   {}
get_type_code()2571   Log_event_type get_type_code()
2572   {
2573     return sql_ex.new_format() ? NEW_LOAD_EVENT: LOAD_EVENT;
2574   }
2575 #ifdef MYSQL_SERVER
2576   bool write_data_header(IO_CACHE* file);
2577   bool write_data_body(IO_CACHE* file);
2578 #endif
is_valid()2579   bool is_valid() const { return table_name != 0; }
get_data_size()2580   int get_data_size()
2581   {
2582     return (table_name_len + db_len + 2 + fname_len
2583 	    + LOAD_HEADER_LEN
2584 	    + sql_ex.data_size() + field_block_len + num_fields);
2585   }
2586 
2587 public:        /* !!! Public in this patch to allow old usage */
2588 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
do_apply_event(Relay_log_info const * rli)2589   virtual int do_apply_event(Relay_log_info const* rli)
2590   {
2591     return do_apply_event(thd->slave_net,rli,0);
2592   }
2593 
2594   int do_apply_event(NET *net, Relay_log_info const *rli,
2595                      bool use_rli_only_for_errors);
2596 #endif
2597 };
2598 
2599 extern char server_version[SERVER_VERSION_LENGTH];
2600 
2601 /**
2602   @class Start_log_event_v3
2603 
2604   Start_log_event_v3 is the Start_log_event of binlog format 3 (MySQL 3.23 and
2605   4.x).
2606 
2607   Format_description_log_event derives from Start_log_event_v3; it is
2608   the Start_log_event of binlog format 4 (MySQL 5.0), that is, the
2609   event that describes the other events' Common-Header/Post-Header
2610   lengths. This event is sent by MySQL 5.0 whenever it starts sending
2611   a new binlog if the requested position is >4 (otherwise if ==4 the
2612   event will be sent naturally).
2613 
2614   @section Start_log_event_v3_binary_format Binary Format
2615 */
2616 class Start_log_event_v3: public Log_event
2617 {
2618 public:
2619   /*
2620     If this event is at the start of the first binary log since server
2621     startup 'created' should be the timestamp when the event (and the
2622     binary log) was created.  In the other case (i.e. this event is at
2623     the start of a binary log created by FLUSH LOGS or automatic
2624     rotation), 'created' should be 0.  This "trick" is used by MySQL
2625     >=4.0.14 slaves to know whether they must drop stale temporary
2626     tables and whether they should abort unfinished transaction.
2627 
2628     Note that when 'created'!=0, it is always equal to the event's
2629     timestamp; indeed Start_log_event is written only in log.cc where
2630     the first constructor below is called, in which 'created' is set
2631     to 'when'.  So in fact 'created' is a useless variable. When it is
2632     0 we can read the actual value from timestamp ('when') and when it
2633     is non-zero we can read the same value from timestamp
2634     ('when'). Conclusion:
2635      - we use timestamp to print when the binlog was created.
2636      - we use 'created' only to know if this is a first binlog or not.
2637      In 3.23.57 we did not pay attention to this identity, so mysqlbinlog in
2638      3.23.57 does not print 'created the_date' if created was zero. This is now
2639      fixed.
2640   */
2641   time_t created;
2642   uint16 binlog_version;
2643   char server_version[ST_SERVER_VER_LEN];
2644   /*
2645     We set this to 1 if we don't want to have the created time in the log,
2646     which is the case when we rollover to a new log.
2647   */
2648   bool dont_set_created;
2649 
2650 #ifdef MYSQL_SERVER
2651   Start_log_event_v3();
2652 #ifdef HAVE_REPLICATION
2653   int pack_info(Protocol* protocol);
2654 #endif /* HAVE_REPLICATION */
2655 #else
Start_log_event_v3()2656   Start_log_event_v3() {}
2657   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
2658 #endif
2659 
2660   Start_log_event_v3(const char* buf, uint event_len,
2661                      const Format_description_log_event* description_event);
~Start_log_event_v3()2662   ~Start_log_event_v3() {}
get_type_code()2663   Log_event_type get_type_code() { return START_EVENT_V3;}
2664 #ifdef MYSQL_SERVER
2665   bool write(IO_CACHE* file);
2666 #endif
is_valid()2667   bool is_valid() const { return server_version[0] != 0; }
get_data_size()2668   int get_data_size()
2669   {
2670     return START_V3_HEADER_LEN; //no variable-sized part
2671   }
2672 
2673 protected:
2674 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
2675   virtual int do_apply_event(Relay_log_info const *rli);
do_shall_skip(Relay_log_info *)2676   virtual enum_skip_reason do_shall_skip(Relay_log_info*)
2677   {
2678     /*
2679       Events from ourself should be skipped, but they should not
2680       decrease the slave skip counter.
2681      */
2682     if (this->server_id == ::server_id)
2683       return Log_event::EVENT_SKIP_IGNORE;
2684     else
2685       return Log_event::EVENT_SKIP_NOT;
2686   }
2687 #endif
2688 };
2689 
2690 
2691 /**
2692   @class Format_description_log_event
2693 
2694   For binlog version 4.
2695   This event is saved by threads which read it, as they need it for future
2696   use (to decode the ordinary events).
2697 
2698   @section Format_description_log_event_binary_format Binary Format
2699 */
2700 
2701 class Format_description_log_event: public Start_log_event_v3
2702 {
2703 public:
2704   /*
2705      The size of the fixed header which _all_ events have
2706      (for binlogs written by this version, this is equal to
2707      LOG_EVENT_HEADER_LEN), except FORMAT_DESCRIPTION_EVENT and ROTATE_EVENT
2708      (those have a header of size LOG_EVENT_MINIMAL_HEADER_LEN).
2709   */
2710   uint8 common_header_len;
2711   uint8 number_of_event_types;
2712   /*
2713      The list of post-headers' lengths followed
2714      by the checksum alg decription byte
2715   */
2716   uint8 *post_header_len;
2717   uchar server_version_split[3];
2718   const uint8 *event_type_permutation;
2719 
2720   Format_description_log_event(uint8 binlog_ver, const char* server_ver=0);
2721   Format_description_log_event(const char* buf, uint event_len,
2722                                const Format_description_log_event
2723                                *description_event);
~Format_description_log_event()2724   ~Format_description_log_event()
2725   {
2726     my_free(post_header_len);
2727   }
get_type_code()2728   Log_event_type get_type_code() { return FORMAT_DESCRIPTION_EVENT;}
2729 #ifdef MYSQL_SERVER
2730   bool write(IO_CACHE* file);
2731 #endif
header_is_valid()2732   bool header_is_valid() const
2733   {
2734     return ((common_header_len >= ((binlog_version==1) ? OLD_HEADER_LEN :
2735                                    LOG_EVENT_MINIMAL_HEADER_LEN)) &&
2736             (post_header_len != NULL));
2737   }
2738 
version_is_valid()2739   bool version_is_valid() const
2740   {
2741     /* It is invalid only when all version numbers are 0 */
2742     return !(server_version_split[0] == 0 &&
2743              server_version_split[1] == 0 &&
2744              server_version_split[2] == 0);
2745   }
2746 
is_valid()2747   bool is_valid() const
2748   {
2749     return header_is_valid() && version_is_valid();
2750   }
2751 
get_data_size()2752   int get_data_size()
2753   {
2754     /*
2755       The vector of post-header lengths is considered as part of the
2756       post-header, because in a given version it never changes (contrary to the
2757       query in a Query_log_event).
2758     */
2759     return FORMAT_DESCRIPTION_HEADER_LEN;
2760   }
2761 
2762   void calc_server_version_split();
2763   ulong get_version_product() const;
2764   bool is_version_before_checksum() const;
2765 protected:
2766 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
2767   virtual int do_apply_event(Relay_log_info const *rli);
2768   virtual int do_update_pos(Relay_log_info *rli);
2769   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
2770 #endif
2771 };
2772 
2773 
2774 /**
2775   @class Intvar_log_event
2776 
2777   An Intvar_log_event will be created just before a Query_log_event,
2778   if the query uses one of the variables LAST_INSERT_ID or INSERT_ID.
2779   Each Intvar_log_event holds the value of one of these variables.
2780 
2781   @section Intvar_log_event_binary_format Binary Format
2782 
2783   The Post-Header for this event type is empty.  The Body has two
2784   components:
2785 
2786   <table>
2787   <caption>Body for Intvar_log_event</caption>
2788 
2789   <tr>
2790     <th>Name</th>
2791     <th>Format</th>
2792     <th>Description</th>
2793   </tr>
2794 
2795   <tr>
2796     <td>type</td>
2797     <td>1 byte enumeration</td>
2798     <td>One byte identifying the type of variable stored.  Currently,
2799     two identifiers are supported:  LAST_INSERT_ID_EVENT==1 and
2800     INSERT_ID_EVENT==2.
2801     </td>
2802   </tr>
2803 
2804   <tr>
2805     <td>value</td>
2806     <td>8 byte unsigned integer</td>
2807     <td>The value of the variable.</td>
2808   </tr>
2809 
2810   </table>
2811 */
2812 class Intvar_log_event: public Log_event
2813 {
2814 public:
2815   ulonglong val;
2816   uchar type;
2817 
2818 #ifdef MYSQL_SERVER
Intvar_log_event(THD * thd_arg,uchar type_arg,ulonglong val_arg,enum_event_cache_type cache_type_arg,enum_event_logging_type logging_type_arg)2819   Intvar_log_event(THD* thd_arg, uchar type_arg, ulonglong val_arg,
2820                    enum_event_cache_type cache_type_arg,
2821                    enum_event_logging_type logging_type_arg)
2822     :Log_event(thd_arg, 0, cache_type_arg, logging_type_arg),
2823     val(val_arg), type(type_arg) { }
2824 #ifdef HAVE_REPLICATION
2825   int pack_info(Protocol* protocol);
2826 #endif /* HAVE_REPLICATION */
2827 #else
2828   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
2829 #endif
2830 
2831   Intvar_log_event(const char* buf,
2832                    const Format_description_log_event *description_event);
~Intvar_log_event()2833   ~Intvar_log_event() {}
get_type_code()2834   Log_event_type get_type_code() { return INTVAR_EVENT;}
2835   const char* get_var_type_name();
get_data_size()2836   int get_data_size() { return  9; /* sizeof(type) + sizeof(val) */;}
2837 #ifdef MYSQL_SERVER
2838   bool write(IO_CACHE* file);
2839 #endif
is_valid()2840   bool is_valid() const { return 1; }
2841 
2842 private:
2843 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
2844   virtual int do_apply_event(Relay_log_info const *rli);
2845   virtual int do_update_pos(Relay_log_info *rli);
2846   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
2847 #endif
2848 };
2849 
2850 
2851 /**
2852   @class Rand_log_event
2853 
2854   Logs random seed used by the next RAND(), and by PASSWORD() in 4.1.0.
2855   4.1.1 does not need it (it's repeatable again) so this event needn't be
2856   written in 4.1.1 for PASSWORD() (but the fact that it is written is just a
2857   waste, it does not cause bugs).
2858 
2859   The state of the random number generation consists of 128 bits,
2860   which are stored internally as two 64-bit numbers.
2861 
2862   @section Rand_log_event_binary_format Binary Format
2863 
2864   The Post-Header for this event type is empty.  The Body has two
2865   components:
2866 
2867   <table>
2868   <caption>Body for Rand_log_event</caption>
2869 
2870   <tr>
2871     <th>Name</th>
2872     <th>Format</th>
2873     <th>Description</th>
2874   </tr>
2875 
2876   <tr>
2877     <td>seed1</td>
2878     <td>8 byte unsigned integer</td>
2879     <td>64 bit random seed1.</td>
2880   </tr>
2881 
2882   <tr>
2883     <td>seed2</td>
2884     <td>8 byte unsigned integer</td>
2885     <td>64 bit random seed2.</td>
2886   </tr>
2887   </table>
2888 */
2889 
2890 class Rand_log_event: public Log_event
2891 {
2892  public:
2893   ulonglong seed1;
2894   ulonglong seed2;
2895 
2896 #ifdef MYSQL_SERVER
Rand_log_event(THD * thd_arg,ulonglong seed1_arg,ulonglong seed2_arg,enum_event_cache_type cache_type_arg,enum_event_logging_type logging_type_arg)2897   Rand_log_event(THD* thd_arg, ulonglong seed1_arg, ulonglong seed2_arg,
2898                  enum_event_cache_type cache_type_arg,
2899                  enum_event_logging_type logging_type_arg)
2900     :Log_event(thd_arg, 0, cache_type_arg, logging_type_arg),
2901     seed1(seed1_arg), seed2(seed2_arg) { }
2902 #ifdef HAVE_REPLICATION
2903   int pack_info(Protocol* protocol);
2904 #endif /* HAVE_REPLICATION */
2905 #else
2906   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
2907 #endif
2908 
2909   Rand_log_event(const char* buf,
2910                  const Format_description_log_event *description_event);
~Rand_log_event()2911   ~Rand_log_event() {}
get_type_code()2912   Log_event_type get_type_code() { return RAND_EVENT;}
get_data_size()2913   int get_data_size() { return 16; /* sizeof(ulonglong) * 2*/ }
2914 #ifdef MYSQL_SERVER
2915   bool write(IO_CACHE* file);
2916 #endif
is_valid()2917   bool is_valid() const { return 1; }
2918 
2919 private:
2920 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
2921   virtual int do_apply_event(Relay_log_info const *rli);
2922   virtual int do_update_pos(Relay_log_info *rli);
2923   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
2924 #endif
2925 };
2926 
2927 /**
2928   @class Xid_log_event
2929 
2930   Logs xid of the transaction-to-be-committed in the 2pc protocol.
2931   Has no meaning in replication, slaves ignore it.
2932 
2933   @section Xid_log_event_binary_format Binary Format
2934 */
2935 #ifdef MYSQL_CLIENT
2936 typedef ulonglong my_xid; // this line is the same as in handler.h
2937 #endif
2938 
2939 class Xid_log_event: public Log_event
2940 {
2941  public:
2942    my_xid xid;
2943 
2944 #ifdef MYSQL_SERVER
Xid_log_event(THD * thd_arg,my_xid x)2945   Xid_log_event(THD* thd_arg, my_xid x)
2946   : Log_event(thd_arg, 0,
2947               Log_event::EVENT_TRANSACTIONAL_CACHE,
2948               Log_event::EVENT_NORMAL_LOGGING),
2949   xid(x)
2950   { }
2951 #ifdef HAVE_REPLICATION
2952   int pack_info(Protocol* protocol);
2953 #endif /* HAVE_REPLICATION */
2954 #else
2955   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
2956 #endif
2957 
2958   Xid_log_event(const char* buf,
2959                 const Format_description_log_event *description_event);
~Xid_log_event()2960   ~Xid_log_event() {}
get_type_code()2961   Log_event_type get_type_code() { return XID_EVENT;}
get_data_size()2962   int get_data_size() { return sizeof(xid); }
2963 #ifdef MYSQL_SERVER
2964   bool write(IO_CACHE* file);
2965 #endif
is_valid()2966   bool is_valid() const { return 1; }
ends_group()2967   virtual bool ends_group() { return TRUE; }
2968 private:
2969 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
2970   virtual int do_apply_event(Relay_log_info const *rli);
2971   virtual int do_apply_event_worker(Slave_worker *rli);
2972   enum_skip_reason do_shall_skip(Relay_log_info *rli);
2973   bool do_commit(THD *thd);
2974 #endif
2975 };
2976 
2977 /**
2978   @class User_var_log_event
2979 
2980   Every time a query uses the value of a user variable, a User_var_log_event is
2981   written before the Query_log_event, to set the user variable.
2982 
2983   @section User_var_log_event_binary_format Binary Format
2984 */
2985 
2986 class User_var_log_event: public Log_event
2987 {
2988 public:
2989   enum {
2990     UNDEF_F= 0,
2991     UNSIGNED_F= 1
2992   };
2993   const char *name;
2994   uint name_len;
2995   char *val;
2996   ulong val_len;
2997   Item_result type;
2998   uint charset_number;
2999   bool is_null;
3000   uchar flags;
3001 #ifdef MYSQL_SERVER
3002   bool deferred;
3003   query_id_t query_id;
User_var_log_event(THD * thd_arg,const char * name_arg,uint name_len_arg,char * val_arg,ulong val_len_arg,Item_result type_arg,uint charset_number_arg,uchar flags_arg,enum_event_cache_type cache_type_arg,enum_event_logging_type logging_type_arg)3004   User_var_log_event(THD* thd_arg, const char *name_arg, uint name_len_arg,
3005                      char *val_arg, ulong val_len_arg, Item_result type_arg,
3006 		     uint charset_number_arg, uchar flags_arg,
3007                      enum_event_cache_type cache_type_arg,
3008                      enum_event_logging_type logging_type_arg)
3009     :Log_event(thd_arg, 0, cache_type_arg, logging_type_arg), name(name_arg),
3010      name_len(name_len_arg), val(val_arg), val_len(val_len_arg), type(type_arg),
3011      charset_number(charset_number_arg), flags(flags_arg), deferred(false)
3012     {
3013       is_null= !val;
3014     }
3015   int pack_info(Protocol* protocol);
3016 #else
3017   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3018 #endif
3019 
3020   User_var_log_event(const char* buf, uint event_len,
3021                      const Format_description_log_event *description_event);
~User_var_log_event()3022   ~User_var_log_event() {}
get_type_code()3023   Log_event_type get_type_code() { return USER_VAR_EVENT;}
3024 #ifdef MYSQL_SERVER
3025   bool write(IO_CACHE* file);
3026   /*
3027      Getter and setter for deferred User-event.
3028      Returns true if the event is not applied directly
3029      and which case the applier adjusts execution path.
3030   */
is_deferred()3031   bool is_deferred() { return deferred; }
3032   /*
3033     In case of the deffered applying the variable instance is flagged
3034     and the parsing time query id is stored to be used at applying time.
3035   */
set_deferred(query_id_t qid)3036   void set_deferred(query_id_t qid) { deferred= true; query_id= qid; }
3037 #endif
is_valid()3038   bool is_valid() const { return name != 0; }
3039 
3040 private:
3041 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3042   virtual int do_apply_event(Relay_log_info const *rli);
3043   virtual int do_update_pos(Relay_log_info *rli);
3044   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
3045 #endif
3046 };
3047 
3048 
3049 /**
3050   @class Stop_log_event
3051 
3052   @section Stop_log_event_binary_format Binary Format
3053 
3054   The Post-Header and Body for this event type are empty; it only has
3055   the Common-Header.
3056 */
3057 class Stop_log_event: public Log_event
3058 {
3059 public:
3060 #ifdef MYSQL_SERVER
Stop_log_event()3061   Stop_log_event() :Log_event()
3062   {}
3063 #else
3064   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3065 #endif
3066 
Stop_log_event(const char * buf,const Format_description_log_event * description_event)3067   Stop_log_event(const char* buf,
3068                  const Format_description_log_event *description_event):
3069     Log_event(buf, description_event)
3070   {}
~Stop_log_event()3071   ~Stop_log_event() {}
get_type_code()3072   Log_event_type get_type_code() { return STOP_EVENT;}
is_valid()3073   bool is_valid() const { return 1; }
3074 
3075 private:
3076 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3077   virtual int do_update_pos(Relay_log_info *rli);
do_shall_skip(Relay_log_info * rli)3078   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli)
3079   {
3080     /*
3081       Events from ourself should be skipped, but they should not
3082       decrease the slave skip counter.
3083      */
3084     if (this->server_id == ::server_id)
3085       return Log_event::EVENT_SKIP_IGNORE;
3086     else
3087       return Log_event::EVENT_SKIP_NOT;
3088   }
3089 #endif
3090 };
3091 
3092 /**
3093   @class Rotate_log_event
3094 
3095   This will be deprecated when we move to using sequence ids.
3096 
3097   @section Rotate_log_event_binary_format Binary Format
3098 
3099   The Post-Header has one component:
3100 
3101   <table>
3102   <caption>Post-Header for Rotate_log_event</caption>
3103 
3104   <tr>
3105     <th>Name</th>
3106     <th>Format</th>
3107     <th>Description</th>
3108   </tr>
3109 
3110   <tr>
3111     <td>position</td>
3112     <td>8 byte integer</td>
3113     <td>The position within the binlog to rotate to.</td>
3114   </tr>
3115 
3116   </table>
3117 
3118   The Body has one component:
3119 
3120   <table>
3121   <caption>Body for Rotate_log_event</caption>
3122 
3123   <tr>
3124     <th>Name</th>
3125     <th>Format</th>
3126     <th>Description</th>
3127   </tr>
3128 
3129   <tr>
3130     <td>new_log</td>
3131     <td>variable length string without trailing zero, extending to the
3132     end of the event (determined by the length field of the
3133     Common-Header)
3134     </td>
3135     <td>Name of the binlog to rotate to.</td>
3136   </tr>
3137 
3138   </table>
3139 */
3140 
3141 class Rotate_log_event: public Log_event
3142 {
3143 public:
3144   enum {
3145     DUP_NAME= 2, // if constructor should dup the string argument
3146     RELAY_LOG=4  // rotate event for relay log
3147   };
3148   const char* new_log_ident;
3149   ulonglong pos;
3150   uint ident_len;
3151   uint flags;
3152 #ifdef MYSQL_SERVER
3153   Rotate_log_event(const char* new_log_ident_arg,
3154 		   uint ident_len_arg,
3155 		   ulonglong pos_arg, uint flags);
3156 #ifdef HAVE_REPLICATION
3157   int pack_info(Protocol* protocol);
3158 #endif /* HAVE_REPLICATION */
3159 #else
3160   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3161 #endif
3162 
3163   Rotate_log_event(const char* buf, uint event_len,
3164                    const Format_description_log_event* description_event);
~Rotate_log_event()3165   ~Rotate_log_event()
3166   {
3167     if (flags & DUP_NAME)
3168       my_free((void*) new_log_ident);
3169   }
get_type_code()3170   Log_event_type get_type_code() { return ROTATE_EVENT;}
get_data_size()3171   int get_data_size() { return  ident_len + ROTATE_HEADER_LEN;}
is_valid()3172   bool is_valid() const { return new_log_ident != 0; }
3173 #ifdef MYSQL_SERVER
3174   bool write(IO_CACHE* file);
3175 #endif
3176 
3177 private:
3178 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3179   virtual int do_update_pos(Relay_log_info *rli);
3180   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
3181 #endif
3182 };
3183 
3184 
3185 /* the classes below are for the new LOAD DATA INFILE logging */
3186 
3187 /**
3188   @class Create_file_log_event
3189 
3190   @section Create_file_log_event_binary_format Binary Format
3191 */
3192 
3193 class Create_file_log_event: public Load_log_event
3194 {
3195 protected:
3196   /*
3197     Pretend we are Load event, so we can write out just
3198     our Load part - used on the slave when writing event out to
3199     SQL_LOAD-*.info file
3200   */
3201   bool fake_base;
3202 public:
3203   uchar* block;
3204   const char *event_buf;
3205   uint block_len;
3206   uint file_id;
3207   bool inited_from_old;
3208 
3209 #ifdef MYSQL_SERVER
3210   Create_file_log_event(THD* thd, sql_exchange* ex, const char* db_arg,
3211 			const char* table_name_arg,
3212 			List<Item>& fields_arg,
3213                         bool is_concurrent_arg,
3214 			enum enum_duplicates handle_dup, bool ignore,
3215 			uchar* block_arg, uint block_len_arg,
3216 			bool using_trans);
3217 #ifdef HAVE_REPLICATION
3218   int pack_info(Protocol* protocol);
3219 #endif /* HAVE_REPLICATION */
3220 #else
3221   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3222   void print(FILE* file, PRINT_EVENT_INFO* print_event_info,
3223              bool enable_local);
3224 #endif
3225 
3226   Create_file_log_event(const char* buf, uint event_len,
3227                         const Format_description_log_event* description_event);
~Create_file_log_event()3228   ~Create_file_log_event()
3229   {
3230     my_free((void*) event_buf);
3231   }
3232 
get_type_code()3233   Log_event_type get_type_code()
3234   {
3235     return fake_base ? Load_log_event::get_type_code() : CREATE_FILE_EVENT;
3236   }
get_data_size()3237   int get_data_size()
3238   {
3239     return (fake_base ? Load_log_event::get_data_size() :
3240 	    Load_log_event::get_data_size() +
3241 	    4 + 1 + block_len);
3242   }
is_valid()3243   bool is_valid() const { return inited_from_old || block != 0; }
3244 #ifdef MYSQL_SERVER
3245   bool write_data_header(IO_CACHE* file);
3246   bool write_data_body(IO_CACHE* file);
3247   /*
3248     Cut out Create_file extentions and
3249     write it as Load event - used on the slave
3250   */
3251   bool write_base(IO_CACHE* file);
3252 #endif
3253 
3254 private:
3255 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3256   virtual int do_apply_event(Relay_log_info const *rli);
3257 #endif
3258 };
3259 
3260 
3261 /**
3262   @class Append_block_log_event
3263 
3264   @section Append_block_log_event_binary_format Binary Format
3265 */
3266 
3267 class Append_block_log_event: public Log_event
3268 {
3269 public:
3270   uchar* block;
3271   uint block_len;
3272   uint file_id;
3273   /*
3274     'db' is filled when the event is created in mysql_load() (the
3275     event needs to have a 'db' member to be well filtered by
3276     binlog-*-db rules). 'db' is not written to the binlog (it's not
3277     used by Append_block_log_event::write()), so it can't be read in
3278     the Append_block_log_event(const char* buf, int event_len)
3279     constructor.  In other words, 'db' is used only for filtering by
3280     binlog-*-db rules.  Create_file_log_event is different: it's 'db'
3281     (which is inherited from Load_log_event) is written to the binlog
3282     and can be re-read.
3283   */
3284   const char* db;
3285 
3286 #ifdef MYSQL_SERVER
3287   Append_block_log_event(THD* thd, const char* db_arg, uchar* block_arg,
3288 			 uint block_len_arg, bool using_trans);
3289 #ifdef HAVE_REPLICATION
3290   int pack_info(Protocol* protocol);
3291   virtual int get_create_or_append() const;
3292 #endif /* HAVE_REPLICATION */
3293 #else
3294   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3295 #endif
3296 
3297   Append_block_log_event(const char* buf, uint event_len,
3298                          const Format_description_log_event
3299                          *description_event);
~Append_block_log_event()3300   ~Append_block_log_event() {}
get_type_code()3301   Log_event_type get_type_code() { return APPEND_BLOCK_EVENT;}
get_data_size()3302   int get_data_size() { return  block_len + APPEND_BLOCK_HEADER_LEN ;}
is_valid()3303   bool is_valid() const { return block != 0; }
3304 #ifdef MYSQL_SERVER
3305   bool write(IO_CACHE* file);
get_db()3306   const char* get_db() { return db; }
3307 #endif
3308 
3309 private:
3310 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3311   virtual int do_apply_event(Relay_log_info const *rli);
3312 #endif
3313 };
3314 
3315 
3316 /**
3317   @class Delete_file_log_event
3318 
3319   @section Delete_file_log_event_binary_format Binary Format
3320 */
3321 
3322 class Delete_file_log_event: public Log_event
3323 {
3324 public:
3325   uint file_id;
3326   const char* db; /* see comment in Append_block_log_event */
3327 
3328 #ifdef MYSQL_SERVER
3329   Delete_file_log_event(THD* thd, const char* db_arg, bool using_trans);
3330 #ifdef HAVE_REPLICATION
3331   int pack_info(Protocol* protocol);
3332 #endif /* HAVE_REPLICATION */
3333 #else
3334   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3335   void print(FILE* file, PRINT_EVENT_INFO* print_event_info,
3336              bool enable_local);
3337 #endif
3338 
3339   Delete_file_log_event(const char* buf, uint event_len,
3340                         const Format_description_log_event* description_event);
~Delete_file_log_event()3341   ~Delete_file_log_event() {}
get_type_code()3342   Log_event_type get_type_code() { return DELETE_FILE_EVENT;}
get_data_size()3343   int get_data_size() { return DELETE_FILE_HEADER_LEN ;}
is_valid()3344   bool is_valid() const { return file_id != 0; }
3345 #ifdef MYSQL_SERVER
3346   bool write(IO_CACHE* file);
get_db()3347   const char* get_db() { return db; }
3348 #endif
3349 
3350 private:
3351 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3352   virtual int do_apply_event(Relay_log_info const *rli);
3353 #endif
3354 };
3355 
3356 
3357 /**
3358   @class Execute_load_log_event
3359 
3360   @section Delete_file_log_event_binary_format Binary Format
3361 */
3362 
3363 class Execute_load_log_event: public Log_event
3364 {
3365 public:
3366   uint file_id;
3367   const char* db; /* see comment in Append_block_log_event */
3368 
3369 #ifdef MYSQL_SERVER
3370   Execute_load_log_event(THD* thd, const char* db_arg, bool using_trans);
3371 #ifdef HAVE_REPLICATION
3372   int pack_info(Protocol* protocol);
3373 #endif /* HAVE_REPLICATION */
3374 #else
3375   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3376 #endif
3377 
3378   Execute_load_log_event(const char* buf, uint event_len,
3379                          const Format_description_log_event
3380                          *description_event);
~Execute_load_log_event()3381   ~Execute_load_log_event() {}
get_type_code()3382   Log_event_type get_type_code() { return EXEC_LOAD_EVENT;}
get_data_size()3383   int get_data_size() { return  EXEC_LOAD_HEADER_LEN ;}
is_valid()3384   bool is_valid() const { return file_id != 0; }
3385 #ifdef MYSQL_SERVER
3386   bool write(IO_CACHE* file);
get_db()3387   const char* get_db() { return db; }
3388 #endif
3389 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
mts_number_dbs()3390   virtual uint8 mts_number_dbs() { return OVER_MAX_DBS_IN_EVENT_MTS; }
3391   /**
3392      @param[out] arg pointer to a struct containing char* array
3393                      pointers be filled in and the number of
3394                      filled instances.
3395 
3396      @return     number of databases in the array (must be one).
3397   */
get_mts_dbs(Mts_db_names * arg)3398   virtual uint8 get_mts_dbs(Mts_db_names *arg)
3399   {
3400     return arg->num= mts_number_dbs();
3401   }
3402 #endif
3403 
3404 private:
3405 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3406   virtual int do_apply_event(Relay_log_info const *rli);
3407 #endif
3408 };
3409 
3410 
3411 /**
3412   @class Begin_load_query_log_event
3413 
3414   Event for the first block of file to be loaded, its only difference from
3415   Append_block event is that this event creates or truncates existing file
3416   before writing data.
3417 
3418   @section Begin_load_query_log_event_binary_format Binary Format
3419 */
3420 class Begin_load_query_log_event: public Append_block_log_event
3421 {
3422 public:
3423 #ifdef MYSQL_SERVER
3424   Begin_load_query_log_event(THD* thd_arg, const char *db_arg,
3425                              uchar* block_arg, uint block_len_arg,
3426                              bool using_trans);
3427 #ifdef HAVE_REPLICATION
3428   Begin_load_query_log_event(THD* thd);
3429   int get_create_or_append() const;
3430 #endif /* HAVE_REPLICATION */
3431 #endif
3432   Begin_load_query_log_event(const char* buf, uint event_len,
3433                              const Format_description_log_event
3434                              *description_event);
~Begin_load_query_log_event()3435   ~Begin_load_query_log_event() {}
get_type_code()3436   Log_event_type get_type_code() { return BEGIN_LOAD_QUERY_EVENT; }
3437 private:
3438 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3439   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
3440 #endif
3441 };
3442 
3443 
3444 /*
3445   Elements of this enum describe how LOAD DATA handles duplicates.
3446 */
3447 enum enum_load_dup_handling { LOAD_DUP_ERROR= 0, LOAD_DUP_IGNORE,
3448                               LOAD_DUP_REPLACE };
3449 
3450 /**
3451   @class Execute_load_query_log_event
3452 
3453   Event responsible for LOAD DATA execution, it similar to Query_log_event
3454   but before executing the query it substitutes original filename in LOAD DATA
3455   query with name of temporary file.
3456 
3457   @section Execute_load_query_log_event_binary_format Binary Format
3458 */
3459 class Execute_load_query_log_event: public Query_log_event
3460 {
3461 public:
3462   uint file_id;       // file_id of temporary file
3463   uint fn_pos_start;  // pointer to the part of the query that should
3464                       // be substituted
3465   uint fn_pos_end;    // pointer to the end of this part of query
3466   /*
3467     We have to store type of duplicate handling explicitly, because
3468     for LOAD DATA it also depends on LOCAL option. And this part
3469     of query will be rewritten during replication so this information
3470     may be lost...
3471   */
3472   enum_load_dup_handling dup_handling;
3473 
3474 #ifdef MYSQL_SERVER
3475   Execute_load_query_log_event(THD* thd, const char* query_arg,
3476                                ulong query_length, uint fn_pos_start_arg,
3477                                uint fn_pos_end_arg,
3478                                enum_load_dup_handling dup_handling_arg,
3479                                bool using_trans, bool immediate,
3480                                bool suppress_use, int errcode);
3481 #ifdef HAVE_REPLICATION
3482   int pack_info(Protocol* protocol);
3483 #endif /* HAVE_REPLICATION */
3484 #else
3485   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
3486   /* Prints the query as LOAD DATA LOCAL and with rewritten filename */
3487   void print(FILE* file, PRINT_EVENT_INFO* print_event_info,
3488 	     const char *local_fname);
3489 #endif
3490   Execute_load_query_log_event(const char* buf, uint event_len,
3491                                const Format_description_log_event
3492                                *description_event);
~Execute_load_query_log_event()3493   ~Execute_load_query_log_event() {}
3494 
get_type_code()3495   Log_event_type get_type_code() { return EXECUTE_LOAD_QUERY_EVENT; }
is_valid()3496   bool is_valid() const { return Query_log_event::is_valid() && file_id != 0; }
3497 
3498   ulong get_post_header_size_for_derived();
3499 #ifdef MYSQL_SERVER
3500   bool write_post_header_for_derived(IO_CACHE* file);
3501 #endif
3502 
3503 private:
3504 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3505   virtual int do_apply_event(Relay_log_info const *rli);
3506 #endif
3507 };
3508 
3509 
3510 #ifdef MYSQL_CLIENT
3511 /**
3512   @class Unknown_log_event
3513 
3514   @section Unknown_log_event_binary_format Binary Format
3515 */
3516 class Unknown_log_event: public Log_event
3517 {
3518 public:
3519   /*
3520     Even if this is an unknown event, we still pass description_event to
3521     Log_event's ctor, this way we can extract maximum information from the
3522     event's header (the unique ID for example).
3523   */
Unknown_log_event(const char * buf,const Format_description_log_event * description_event)3524   Unknown_log_event(const char* buf,
3525                     const Format_description_log_event *description_event):
3526     Log_event(buf, description_event)
3527   {}
~Unknown_log_event()3528   ~Unknown_log_event() {}
3529   void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
get_type_code()3530   Log_event_type get_type_code() { return UNKNOWN_EVENT;}
is_valid()3531   bool is_valid() const { return 1; }
3532 };
3533 #endif
3534 char *str_to_hex(char *to, const char *from, uint len);
3535 
3536 /**
3537   @class Table_map_log_event
3538 
3539   In row-based mode, every row operation event is preceded by a
3540   Table_map_log_event which maps a table definition to a number.  The
3541   table definition consists of database name, table name, and column
3542   definitions.
3543 
3544   @section Table_map_log_event_binary_format Binary Format
3545 
3546   The Post-Header has the following components:
3547 
3548   <table>
3549   <caption>Post-Header for Table_map_log_event</caption>
3550 
3551   <tr>
3552     <th>Name</th>
3553     <th>Format</th>
3554     <th>Description</th>
3555   </tr>
3556 
3557   <tr>
3558     <td>table_id</td>
3559     <td>6 bytes unsigned integer</td>
3560     <td>The number that identifies the table.</td>
3561   </tr>
3562 
3563   <tr>
3564     <td>flags</td>
3565     <td>2 byte bitfield</td>
3566     <td>Reserved for future use; currently always 0.</td>
3567   </tr>
3568 
3569   </table>
3570 
3571   The Body has the following components:
3572 
3573   <table>
3574   <caption>Body for Table_map_log_event</caption>
3575 
3576   <tr>
3577     <th>Name</th>
3578     <th>Format</th>
3579     <th>Description</th>
3580   </tr>
3581 
3582   <tr>
3583     <td>database_name</td>
3584     <td>one byte string length, followed by null-terminated string</td>
3585     <td>The name of the database in which the table resides.  The name
3586     is represented as a one byte unsigned integer representing the
3587     number of bytes in the name, followed by length bytes containing
3588     the database name, followed by a terminating 0 byte.  (Note the
3589     redundancy in the representation of the length.)  </td>
3590   </tr>
3591 
3592   <tr>
3593     <td>table_name</td>
3594     <td>one byte string length, followed by null-terminated string</td>
3595     <td>The name of the table, encoded the same way as the database
3596     name above.</td>
3597   </tr>
3598 
3599   <tr>
3600     <td>column_count</td>
3601     <td>@ref packed_integer "Packed Integer"</td>
3602     <td>The number of columns in the table, represented as a packed
3603     variable-length integer.</td>
3604   </tr>
3605 
3606   <tr>
3607     <td>column_type</td>
3608     <td>List of column_count 1 byte enumeration values</td>
3609     <td>The type of each column in the table, listed from left to
3610     right.  Each byte is mapped to a column type according to the
3611     enumeration type enum_field_types defined in mysql_com.h.  The
3612     mapping of types to numbers is listed in the table @ref
3613     Table_table_map_log_event_column_types "below" (along with
3614     description of the associated metadata field).  </td>
3615   </tr>
3616 
3617   <tr>
3618     <td>metadata_length</td>
3619     <td>@ref packed_integer "Packed Integer"</td>
3620     <td>The length of the following metadata block</td>
3621   </tr>
3622 
3623   <tr>
3624     <td>metadata</td>
3625     <td>list of metadata for each column</td>
3626     <td>For each column from left to right, a chunk of data who's
3627     length and semantics depends on the type of the column.  The
3628     length and semantics for the metadata for each column are listed
3629     in the table @ref Table_table_map_log_event_column_types
3630     "below".</td>
3631   </tr>
3632 
3633   <tr>
3634     <td>null_bits</td>
3635     <td>column_count bits, rounded up to nearest byte</td>
3636     <td>For each column, a bit indicating whether data in the column
3637     can be NULL or not.  The number of bytes needed for this is
3638     int((column_count+7)/8).  The flag for the first column from the
3639     left is in the least-significant bit of the first byte, the second
3640     is in the second least significant bit of the first byte, the
3641     ninth is in the least significant bit of the second byte, and so
3642     on.  </td>
3643   </tr>
3644 
3645   </table>
3646 
3647   The table below lists all column types, along with the numerical
3648   identifier for it and the size and interpretation of meta-data used
3649   to describe the type.
3650 
3651   @anchor Table_table_map_log_event_column_types
3652   <table>
3653   <caption>Table_map_log_event column types: numerical identifier and
3654   metadata</caption>
3655   <tr>
3656     <th>Name</th>
3657     <th>Identifier</th>
3658     <th>Size of metadata in bytes</th>
3659     <th>Description of metadata</th>
3660   </tr>
3661 
3662   <tr>
3663     <td>MYSQL_TYPE_DECIMAL</td><td>0</td>
3664     <td>0</td>
3665     <td>No column metadata.</td>
3666   </tr>
3667 
3668   <tr>
3669     <td>MYSQL_TYPE_TINY</td><td>1</td>
3670     <td>0</td>
3671     <td>No column metadata.</td>
3672   </tr>
3673 
3674   <tr>
3675     <td>MYSQL_TYPE_SHORT</td><td>2</td>
3676     <td>0</td>
3677     <td>No column metadata.</td>
3678   </tr>
3679 
3680   <tr>
3681     <td>MYSQL_TYPE_LONG</td><td>3</td>
3682     <td>0</td>
3683     <td>No column metadata.</td>
3684   </tr>
3685 
3686   <tr>
3687     <td>MYSQL_TYPE_FLOAT</td><td>4</td>
3688     <td>1 byte</td>
3689     <td>1 byte unsigned integer, representing the "pack_length", which
3690     is equal to sizeof(float) on the server from which the event
3691     originates.</td>
3692   </tr>
3693 
3694   <tr>
3695     <td>MYSQL_TYPE_DOUBLE</td><td>5</td>
3696     <td>1 byte</td>
3697     <td>1 byte unsigned integer, representing the "pack_length", which
3698     is equal to sizeof(double) on the server from which the event
3699     originates.</td>
3700   </tr>
3701 
3702   <tr>
3703     <td>MYSQL_TYPE_NULL</td><td>6</td>
3704     <td>0</td>
3705     <td>No column metadata.</td>
3706   </tr>
3707 
3708   <tr>
3709     <td>MYSQL_TYPE_TIMESTAMP</td><td>7</td>
3710     <td>0</td>
3711     <td>No column metadata.</td>
3712   </tr>
3713 
3714   <tr>
3715     <td>MYSQL_TYPE_LONGLONG</td><td>8</td>
3716     <td>0</td>
3717     <td>No column metadata.</td>
3718   </tr>
3719 
3720   <tr>
3721     <td>MYSQL_TYPE_INT24</td><td>9</td>
3722     <td>0</td>
3723     <td>No column metadata.</td>
3724   </tr>
3725 
3726   <tr>
3727     <td>MYSQL_TYPE_DATE</td><td>10</td>
3728     <td>0</td>
3729     <td>No column metadata.</td>
3730   </tr>
3731 
3732   <tr>
3733     <td>MYSQL_TYPE_TIME</td><td>11</td>
3734     <td>0</td>
3735     <td>No column metadata.</td>
3736   </tr>
3737 
3738   <tr>
3739     <td>MYSQL_TYPE_DATETIME</td><td>12</td>
3740     <td>0</td>
3741     <td>No column metadata.</td>
3742   </tr>
3743 
3744   <tr>
3745     <td>MYSQL_TYPE_YEAR</td><td>13</td>
3746     <td>0</td>
3747     <td>No column metadata.</td>
3748   </tr>
3749 
3750   <tr>
3751     <td><i>MYSQL_TYPE_NEWDATE</i></td><td><i>14</i></td>
3752     <td>&ndash;</td>
3753     <td><i>This enumeration value is only used internally and cannot
3754     exist in a binlog.</i></td>
3755   </tr>
3756 
3757   <tr>
3758     <td>MYSQL_TYPE_VARCHAR</td><td>15</td>
3759     <td>2 bytes</td>
3760     <td>2 byte unsigned integer representing the maximum length of
3761     the string.</td>
3762   </tr>
3763 
3764   <tr>
3765     <td>MYSQL_TYPE_BIT</td><td>16</td>
3766     <td>2 bytes</td>
3767     <td>A 1 byte unsigned int representing the length in bits of the
3768     bitfield (0 to 64), followed by a 1 byte unsigned int
3769     representing the number of bytes occupied by the bitfield.  The
3770     number of bytes is either int((length+7)/8) or int(length/8).</td>
3771   </tr>
3772 
3773   <tr>
3774     <td>MYSQL_TYPE_NEWDECIMAL</td><td>246</td>
3775     <td>2 bytes</td>
3776     <td>A 1 byte unsigned int representing the precision, followed
3777     by a 1 byte unsigned int representing the number of decimals.</td>
3778   </tr>
3779 
3780   <tr>
3781     <td><i>MYSQL_TYPE_ENUM</i></td><td><i>247</i></td>
3782     <td>&ndash;</td>
3783     <td><i>This enumeration value is only used internally and cannot
3784     exist in a binlog.</i></td>
3785   </tr>
3786 
3787   <tr>
3788     <td><i>MYSQL_TYPE_SET</i></td><td><i>248</i></td>
3789     <td>&ndash;</td>
3790     <td><i>This enumeration value is only used internally and cannot
3791     exist in a binlog.</i></td>
3792   </tr>
3793 
3794   <tr>
3795     <td>MYSQL_TYPE_TINY_BLOB</td><td>249</td>
3796     <td>&ndash;</td>
3797     <td><i>This enumeration value is only used internally and cannot
3798     exist in a binlog.</i></td>
3799   </tr>
3800 
3801   <tr>
3802     <td><i>MYSQL_TYPE_MEDIUM_BLOB</i></td><td><i>250</i></td>
3803     <td>&ndash;</td>
3804     <td><i>This enumeration value is only used internally and cannot
3805     exist in a binlog.</i></td>
3806   </tr>
3807 
3808   <tr>
3809     <td><i>MYSQL_TYPE_LONG_BLOB</i></td><td><i>251</i></td>
3810     <td>&ndash;</td>
3811     <td><i>This enumeration value is only used internally and cannot
3812     exist in a binlog.</i></td>
3813   </tr>
3814 
3815   <tr>
3816     <td>MYSQL_TYPE_BLOB</td><td>252</td>
3817     <td>1 byte</td>
3818     <td>The pack length, i.e., the number of bytes needed to represent
3819     the length of the blob: 1, 2, 3, or 4.</td>
3820   </tr>
3821 
3822   <tr>
3823     <td>MYSQL_TYPE_VAR_STRING</td><td>253</td>
3824     <td>2 bytes</td>
3825     <td>This is used to store both strings and enumeration values.
3826     The first byte is a enumeration value storing the <i>real
3827     type</i>, which may be either MYSQL_TYPE_VAR_STRING or
3828     MYSQL_TYPE_ENUM.  The second byte is a 1 byte unsigned integer
3829     representing the field size, i.e., the number of bytes needed to
3830     store the length of the string.</td>
3831   </tr>
3832 
3833   <tr>
3834     <td>MYSQL_TYPE_STRING</td><td>254</td>
3835     <td>2 bytes</td>
3836     <td>The first byte is always MYSQL_TYPE_VAR_STRING (i.e., 253).
3837     The second byte is the field size, i.e., the number of bytes in
3838     the representation of size of the string: 3 or 4.</td>
3839   </tr>
3840 
3841   <tr>
3842     <td>MYSQL_TYPE_GEOMETRY</td><td>255</td>
3843     <td>1 byte</td>
3844     <td>The pack length, i.e., the number of bytes needed to represent
3845     the length of the geometry: 1, 2, 3, or 4.</td>
3846   </tr>
3847 
3848   </table>
3849 */
3850 class Table_map_log_event : public Log_event
3851 {
3852 public:
3853   /* Constants */
3854   enum
3855   {
3856     TYPE_CODE = TABLE_MAP_EVENT
3857   };
3858 
3859   /**
3860      Enumeration of the errors that can be returned.
3861    */
3862   enum enum_error
3863   {
3864     ERR_OPEN_FAILURE = -1,               /**< Failure to open table */
3865     ERR_OK = 0,                                 /**< No error */
3866     ERR_TABLE_LIMIT_EXCEEDED = 1,      /**< No more room for tables */
3867     ERR_OUT_OF_MEM = 2,                         /**< Out of memory */
3868     ERR_BAD_TABLE_DEF = 3,     /**< Table definition does not match */
3869     ERR_RBR_TO_SBR = 4  /**< daisy-chanining RBR to SBR not allowed */
3870   };
3871 
3872   enum enum_flag
3873   {
3874     /*
3875        Nothing here right now, but the flags support is there in
3876        preparation for changes that are coming.  Need to add a
3877        constant to make it compile under HP-UX: aCC does not like
3878        empty enumerations.
3879     */
3880     ENUM_FLAG_COUNT
3881   };
3882 
3883   typedef uint16 flag_set;
3884 
3885   /* Special constants representing sets of flags */
3886   enum
3887   {
3888     TM_NO_FLAGS = 0U,
3889     TM_BIT_LEN_EXACT_F = (1U << 0),
3890     TM_REFERRED_FK_DB_F = (1U << 1)
3891   };
3892 
get_flags(flag_set flag)3893   flag_set get_flags(flag_set flag) const { return m_flags & flag; }
3894 
3895 #ifdef MYSQL_SERVER
3896   Table_map_log_event(THD *thd, TABLE *tbl, const Table_id& tid,
3897                       bool is_transactional);
3898 #endif
3899 #ifdef HAVE_REPLICATION
3900   Table_map_log_event(const char *buf, uint event_len,
3901                       const Format_description_log_event *description_event);
3902 #endif
3903 
3904   ~Table_map_log_event();
3905 
3906 #ifdef MYSQL_CLIENT
create_table_def()3907   table_def *create_table_def()
3908   {
3909     return new table_def(m_coltype, m_colcnt, m_field_metadata,
3910                          m_field_metadata_size, m_null_bits, m_flags);
3911   }
3912 #endif
get_table_id()3913   const Table_id& get_table_id() const { return m_table_id; }
get_table_name()3914   const char *get_table_name() const { return m_tblnam; }
get_db_name()3915   const char *get_db_name() const    { return m_dbnam; }
3916 #ifdef MYSQL_CLIENT
3917   int rewrite_db(const char* new_name, size_t new_name_len,
3918                  const Format_description_log_event*);
3919 #endif
get_type_code()3920   virtual Log_event_type get_type_code() { return TABLE_MAP_EVENT; }
is_valid()3921   virtual bool is_valid() const { return m_memory != NULL; /* we check malloc */ }
3922 
get_data_size()3923   virtual int get_data_size() { return (uint) m_data_size; }
3924 #ifdef MYSQL_SERVER
3925   virtual int save_field_metadata();
3926   virtual bool write_data_header(IO_CACHE *file);
3927   virtual bool write_data_body(IO_CACHE *file);
get_db()3928   virtual const char *get_db() { return m_dbnam; }
mts_number_dbs()3929   virtual uint8 mts_number_dbs()
3930   {
3931     return get_flags(TM_REFERRED_FK_DB_F) ? OVER_MAX_DBS_IN_EVENT_MTS : 1;
3932   }
3933   /**
3934      @param[out] arg pointer to a struct containing char* array
3935                      pointers be filled in and the number of filled instances.
3936 
3937      @return    number of databases in the array: either one or
3938                 OVER_MAX_DBS_IN_EVENT_MTS, when the Table map event reports
3939                 foreign keys constraint.
3940   */
get_mts_dbs(Mts_db_names * arg)3941   virtual uint8 get_mts_dbs(Mts_db_names *arg)
3942   {
3943     const char *db_name= get_db();
3944 
3945     if (!rpl_filter->is_rewrite_empty() && !get_flags(TM_REFERRED_FK_DB_F))
3946     {
3947       size_t dummy_len;
3948       const char *db_filtered= rpl_filter->get_rewrite_db(db_name, &dummy_len);
3949       // db_name != db_filtered means that db_name is rewritten.
3950       if (strcmp(db_name, db_filtered))
3951         db_name= db_filtered;
3952     }
3953 
3954     if (!get_flags(TM_REFERRED_FK_DB_F))
3955       arg->name[0]= db_name;
3956 
3957     return arg->num= mts_number_dbs();
3958   }
3959 
3960 #endif
3961 
3962 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3963   virtual int pack_info(Protocol *protocol);
3964 #endif
3965 
3966 #ifdef MYSQL_CLIENT
3967   virtual void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
3968 #endif
3969 
3970 
3971 private:
3972 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
3973   virtual int do_apply_event(Relay_log_info const *rli);
3974   virtual int do_update_pos(Relay_log_info *rli);
3975   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
3976 #endif
3977 
3978 #ifdef MYSQL_SERVER
3979   TABLE         *m_table;
3980 #endif
3981   char const    *m_dbnam;
3982   size_t         m_dblen;
3983   char const    *m_tblnam;
3984   size_t         m_tbllen;
3985   ulong          m_colcnt;
3986   uchar         *m_coltype;
3987 
3988   uchar         *m_memory;
3989   Table_id       m_table_id;
3990   flag_set       m_flags;
3991 
3992   size_t         m_data_size;
3993 
3994   uchar          *m_field_metadata;        // buffer for field metadata
3995   /*
3996     The size of field metadata buffer set by calling save_field_metadata()
3997   */
3998   ulong          m_field_metadata_size;
3999   uchar         *m_null_bits;
4000   uchar         *m_meta_memory;
4001 };
4002 
4003 
4004 /**
4005   @class Rows_log_event
4006 
4007  Common base class for all row-containing log events.
4008 
4009  RESPONSIBILITIES
4010 
4011    Encode the common parts of all events containing rows, which are:
4012    - Write data header and data body to an IO_CACHE.
4013    - Provide an interface for adding an individual row to the event.
4014 
4015   @section Rows_log_event_binary_format Binary Format
4016 */
4017 
4018 
4019 class Rows_log_event : public Log_event
4020 {
4021 public:
4022   enum row_lookup_mode {
4023        ROW_LOOKUP_UNDEFINED= 0,
4024        ROW_LOOKUP_NOT_NEEDED= 1,
4025        ROW_LOOKUP_INDEX_SCAN= 2,
4026        ROW_LOOKUP_TABLE_SCAN= 3,
4027        ROW_LOOKUP_HASH_SCAN= 4
4028   };
4029 
4030   /**
4031      Enumeration of the errors that can be returned.
4032    */
4033   enum enum_error
4034   {
4035     ERR_OPEN_FAILURE = -1,               /**< Failure to open table */
4036     ERR_OK = 0,                                 /**< No error */
4037     ERR_TABLE_LIMIT_EXCEEDED = 1,      /**< No more room for tables */
4038     ERR_OUT_OF_MEM = 2,                         /**< Out of memory */
4039     ERR_BAD_TABLE_DEF = 3,     /**< Table definition does not match */
4040     ERR_RBR_TO_SBR = 4  /**< daisy-chanining RBR to SBR not allowed */
4041   };
4042 
4043   /*
4044     These definitions allow you to combine the flags into an
4045     appropriate flag set using the normal bitwise operators.  The
4046     implicit conversion from an enum-constant to an integer is
4047     accepted by the compiler, which is then used to set the real set
4048     of flags.
4049   */
4050   enum enum_flag
4051   {
4052     /* Last event of a statement */
4053     STMT_END_F = (1U << 0),
4054 
4055     /* Value of the OPTION_NO_FOREIGN_KEY_CHECKS flag in thd->options */
4056     NO_FOREIGN_KEY_CHECKS_F = (1U << 1),
4057 
4058     /* Value of the OPTION_RELAXED_UNIQUE_CHECKS flag in thd->options */
4059     RELAXED_UNIQUE_CHECKS_F = (1U << 2),
4060 
4061     /**
4062       Indicates that rows in this event are complete, that is contain
4063       values for all columns of the table.
4064      */
4065     COMPLETE_ROWS_F = (1U << 3)
4066   };
4067 
4068   typedef uint16 flag_set;
4069 
4070   /* Special constants representing sets of flags */
4071   enum
4072   {
4073       RLE_NO_FLAGS = 0U
4074   };
4075 
4076   virtual ~Rows_log_event();
4077 
set_flags(flag_set flags_arg)4078   void set_flags(flag_set flags_arg) { m_flags |= flags_arg; }
clear_flags(flag_set flags_arg)4079   void clear_flags(flag_set flags_arg) { m_flags &= ~flags_arg; }
get_flags(flag_set flags_arg)4080   flag_set get_flags(flag_set flags_arg) const { return m_flags & flags_arg; }
4081 
get_type_code()4082   Log_event_type get_type_code() { return m_type; } /* Specific type (_V1 etc) */
4083   virtual Log_event_type get_general_type_code() = 0; /* General rows op type, no version */
4084 
4085 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4086   virtual int pack_info(Protocol *protocol);
4087 #endif
4088 
4089 #ifdef MYSQL_CLIENT
4090   /* not for direct call, each derived has its own ::print() */
4091   virtual void print(FILE *file, PRINT_EVENT_INFO *print_event_info)= 0;
4092   void print_verbose(IO_CACHE *file,
4093                      PRINT_EVENT_INFO *print_event_info);
4094   size_t print_verbose_one_row(IO_CACHE *file, table_def *td,
4095                                PRINT_EVENT_INFO *print_event_info,
4096                                MY_BITMAP *cols_bitmap,
4097                                const uchar *ptr, const uchar *prefix);
4098 #endif
4099 
4100 #ifdef MYSQL_SERVER
add_row_data(uchar * data,size_t length)4101   int add_row_data(uchar *data, size_t length)
4102   {
4103     return do_add_row_data(data,length);
4104   }
4105 #endif
4106 
4107   /* Member functions to implement superclass interface */
4108   virtual int get_data_size();
4109 
get_cols()4110   MY_BITMAP const *get_cols() const { return &m_cols; }
get_cols_ai()4111   MY_BITMAP const *get_cols_ai() const { return &m_cols_ai; }
get_width()4112   size_t get_width() const          { return m_width; }
get_table_id()4113   const Table_id& get_table_id() const        { return m_table_id; }
4114 
4115 #if defined(MYSQL_SERVER)
4116   /*
4117     This member function compares the table's read/write_set
4118     with this event's m_cols and m_cols_ai. Comparison takes
4119     into account what type of rows event is this: Delete, Write or
4120     Update, therefore it uses the correct m_cols[_ai] according
4121     to the event type code.
4122 
4123     Note that this member function should only be called for the
4124     following events:
4125     - Delete_rows_log_event
4126     - Write_rows_log_event
4127     - Update_rows_log_event
4128 
4129     @param[IN] table The table to compare this events bitmaps
4130                      against.
4131 
4132     @return TRUE if sets match, FALSE otherwise. (following
4133                  bitmap_cmp return logic).
4134 
4135    */
read_write_bitmaps_cmp(TABLE * table)4136   virtual bool read_write_bitmaps_cmp(TABLE *table)
4137   {
4138     bool res= FALSE;
4139 
4140     switch (get_general_type_code())
4141     {
4142       case DELETE_ROWS_EVENT:
4143         res= bitmap_cmp(get_cols(), table->read_set);
4144         break;
4145       case UPDATE_ROWS_EVENT:
4146         res= (bitmap_cmp(get_cols(), table->read_set) &&
4147               bitmap_cmp(get_cols_ai(), table->write_set));
4148         break;
4149       case WRITE_ROWS_EVENT:
4150         res= bitmap_cmp(get_cols(), table->write_set);
4151         break;
4152       default:
4153         /*
4154           We should just compare bitmaps for Delete, Write
4155           or Update rows events.
4156         */
4157         DBUG_ASSERT(0);
4158     }
4159     return res;
4160   }
4161 #endif
4162 
4163 #ifdef MYSQL_SERVER
4164   virtual bool write_data_header(IO_CACHE *file);
4165   virtual bool write_data_body(IO_CACHE *file);
get_db()4166   virtual const char *get_db() { return m_table->s->db.str; }
4167 #endif
4168   /*
4169     Check that malloc() succeeded in allocating memory for the rows
4170     buffer and the COLS vector. Checking that an Update_rows_log_event
4171     is valid is done in the Update_rows_log_event::is_valid()
4172     function.
4173   */
is_valid()4174   virtual bool is_valid() const
4175   {
4176     return m_rows_buf && m_cols.bitmap;
4177   }
4178 
4179   uint     m_row_count;         /* The number of rows added to the event */
4180 
get_extra_row_data()4181   const uchar* get_extra_row_data() const   { return m_extra_row_data; }
4182 
4183 protected:
4184   /*
4185      The constructors are protected since you're supposed to inherit
4186      this class, not create instances of this class.
4187   */
4188 #ifdef MYSQL_SERVER
4189   Rows_log_event(THD*, TABLE*, const Table_id& table_id,
4190 		 MY_BITMAP const *cols, bool is_transactional,
4191                  Log_event_type event_type,
4192                  const uchar* extra_row_info);
4193 #endif
4194   Rows_log_event(const char *row_data, uint event_len,
4195 		 const Format_description_log_event *description_event);
4196 
4197 #ifdef MYSQL_CLIENT
4198   void print_helper(FILE *, PRINT_EVENT_INFO *, char const *const name);
4199 #endif
4200 
4201 #ifdef MYSQL_SERVER
4202   virtual int do_add_row_data(uchar *data, size_t length);
4203 #endif
4204 
4205 #ifdef MYSQL_SERVER
4206   TABLE *m_table;		/* The table the rows belong to */
4207 #endif
4208   Table_id    m_table_id;	/* Table ID */
4209   MY_BITMAP   m_cols;		/* Bitmap denoting columns available */
4210   ulong       m_width;          /* The width of the columns bitmap */
4211 #ifndef MYSQL_CLIENT
4212   /**
4213      Hash table that will hold the entries for while using HASH_SCAN
4214      algorithm to search and update/delete rows.
4215    */
4216   Hash_slave_rows m_hash;
4217 
4218   /**
4219      The algorithm to use while searching for rows using the before
4220      image.
4221   */
4222   uint            m_rows_lookup_algorithm;
4223 #endif
4224   /*
4225     Bitmap for columns available in the after image, if present. These
4226     fields are only available for Update_rows events. Observe that the
4227     width of both the before image COLS vector and the after image
4228     COLS vector is the same: the number of columns of the table on the
4229     master.
4230   */
4231   MY_BITMAP   m_cols_ai;
4232 
4233   ulong       m_master_reclength; /* Length of record on master side */
4234 
4235   /* Bit buffers in the same memory as the class */
4236   uint32    m_bitbuf[128/(sizeof(uint32)*8)];
4237   uint32    m_bitbuf_ai[128/(sizeof(uint32)*8)];
4238 
4239   uchar    *m_rows_buf;		/* The rows in packed format */
4240   uchar    *m_rows_cur;		/* One-after the end of the data */
4241   uchar    *m_rows_end;		/* One-after the end of the allocated space */
4242 
4243   flag_set m_flags;		/* Flags for row-level events */
4244 
4245   Log_event_type m_type;        /* Actual event type */
4246 
4247   uchar    *m_extra_row_data;   /* Pointer to extra row data if any */
4248                                 /* If non null, first byte is length */
4249 
4250   /* helper functions */
4251 
4252 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4253   const uchar *m_curr_row;     /* Start of the row being processed */
4254   const uchar *m_curr_row_end; /* One-after the end of the current row */
4255   uchar    *m_key;      /* Buffer to keep key value during searches */
4256   uint     m_key_index;
4257   KEY      *m_key_info; /* Points to description of index #m_key_index */
4258   class Key_compare
4259   {
4260 public:
4261     /**
4262        @param  ki  Where to find KEY description
4263        @note m_distinct_keys is instantiated when Rows_log_event is constructed; it
4264        stores a Key_compare object internally. However at that moment, the
4265        index (KEY*) to use for comparisons, is not yet known. So, at
4266        instantiation, we indicate the Key_compare the place where it can
4267        find the KEY* when needed (this place is Rows_log_event::m_key_info),
4268        Key_compare remembers the place in member m_key_info.
4269        Before we need to do comparisons - i.e. before we need to insert
4270        elements, we update Rows_log_event::m_key_info once for all.
4271     */
m_key_info(ki)4272     Key_compare(KEY **ki= NULL) : m_key_info(ki) {}
operator()4273     bool operator()(uchar *k1, uchar *k2) const
4274     {
4275       return key_cmp2((*m_key_info)->key_part,
4276                       k1, (*m_key_info)->key_length,
4277                       k2, (*m_key_info)->key_length) < 0 ;
4278     }
4279 private:
4280     KEY **m_key_info;
4281   };
4282   std::set<uchar *, Key_compare> m_distinct_keys;
4283   std::set<uchar *, Key_compare>::iterator m_itr;
4284   /**
4285     A spare buffer which will be used when saving the distinct keys
4286     for doing an index scan with HASH_SCAN search algorithm.
4287   */
4288   uchar *m_distinct_key_spare_buf;
4289 
4290   // Unpack the current row into m_table->record[0]
unpack_current_row(const Relay_log_info * const rli,MY_BITMAP const * cols)4291   int unpack_current_row(const Relay_log_info *const rli,
4292                          MY_BITMAP const *cols)
4293   {
4294     DBUG_ASSERT(m_table);
4295 
4296     ASSERT_OR_RETURN_ERROR(m_curr_row <= m_rows_end, HA_ERR_CORRUPT_EVENT);
4297     return ::unpack_row(rli, m_table, m_width, m_curr_row, cols,
4298                                    &m_curr_row_end, &m_master_reclength, m_rows_end);
4299   }
4300 
4301   /*
4302     This member function is called when deciding the algorithm to be used to
4303     find the rows to be updated on the slave during row based replication.
4304     This this functions sets the m_rows_lookup_algorithm and also the
4305     m_key_index with the key index to be used if the algorithm is dependent on
4306     an index.
4307    */
4308   void decide_row_lookup_algorithm_and_key();
4309 
4310   /*
4311     Encapsulates the  operations to be done before applying
4312     row event for update and delete.
4313    */
4314   int row_operations_scan_and_key_setup();
4315 
4316   /*
4317    Encapsulates the  operations to be done after applying
4318    row event for update and delete.
4319   */
4320   int row_operations_scan_and_key_teardown(int error);
4321 
4322   /**
4323     Helper function to check whether there is an auto increment
4324     column on the table where the event is to be applied.
4325 
4326     @return true if there is an autoincrement field on the extra
4327             columns, false otherwise.
4328    */
is_auto_inc_in_extra_columns()4329   inline bool is_auto_inc_in_extra_columns()
4330   {
4331     DBUG_ASSERT(m_table);
4332     return (m_table->next_number_field &&
4333             m_table->next_number_field->field_index >= m_width);
4334   }
4335 #endif
4336 
4337 private:
4338 
4339 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4340   virtual int do_apply_event(Relay_log_info const *rli);
4341   virtual int do_update_pos(Relay_log_info *rli);
4342   virtual enum_skip_reason do_shall_skip(Relay_log_info *rli);
4343 
4344   /*
4345     Primitive to prepare for a sequence of row executions.
4346 
4347     DESCRIPTION
4348 
4349       Before doing a sequence of do_prepare_row() and do_exec_row()
4350       calls, this member function should be called to prepare for the
4351       entire sequence. Typically, this member function will allocate
4352       space for any buffers that are needed for the two member
4353       functions mentioned above.
4354 
4355     RETURN VALUE
4356 
4357       The member function will return 0 if all went OK, or a non-zero
4358       error code otherwise.
4359   */
4360   virtual
4361   int do_before_row_operations(const Slave_reporting_capability *const log) = 0;
4362 
4363   /*
4364     Primitive to clean up after a sequence of row executions.
4365 
4366     DESCRIPTION
4367 
4368       After doing a sequence of do_prepare_row() and do_exec_row(),
4369       this member function should be called to clean up and release
4370       any allocated buffers.
4371 
4372       The error argument, if non-zero, indicates an error which happened during
4373       row processing before this function was called. In this case, even if
4374       function is successful, it should return the error code given in the argument.
4375   */
4376   virtual
4377   int do_after_row_operations(const Slave_reporting_capability *const log,
4378                               int error) = 0;
4379 
4380   /*
4381     Primitive to do the actual execution necessary for a row.
4382 
4383     DESCRIPTION
4384       The member function will do the actual execution needed to handle a row.
4385       The row is located at m_curr_row. When the function returns,
4386       m_curr_row_end should point at the next row (one byte after the end
4387       of the current row).
4388 
4389     RETURN VALUE
4390       0 if execution succeeded, 1 if execution failed.
4391 
4392   */
4393   virtual int do_exec_row(const Relay_log_info *const rli) = 0;
4394 
4395   /**
4396     Private member function called while handling idempotent errors.
4397 
4398     @param err[IN/OUT] the error to handle. If it is listed as
4399                        idempotent/ignored related error, then it is cleared.
4400     @returns true if the slave should stop executing rows.
4401    */
4402   int handle_idempotent_and_ignored_errors(Relay_log_info const *rli, int *err);
4403 
4404   /**
4405      Private member function called after updating/deleting a row. It
4406      performs some assertions and more importantly, it updates
4407      m_curr_row so that the next row is processed during the row
4408      execution main loop (@c Rows_log_event::do_apply_event()).
4409 
4410      @param err[IN] the current error code.
4411    */
4412   void do_post_row_operations(Relay_log_info const *rli, int err);
4413 
4414   /**
4415      Commodity wrapper around do_exec_row(), that deals with resetting
4416      the thd reference in the table.
4417    */
4418   int do_apply_row(Relay_log_info const *rli);
4419 
4420   /**
4421      Implementation of the index scan and update algorithm. It uses
4422      PK, UK or regular Key to search for the record to update. When
4423      found it updates it.
4424    */
4425   int do_index_scan_and_update(Relay_log_info const *rli);
4426 
4427   /**
4428      Implementation of the hash_scan and update algorithm. It collects
4429      rows positions in a hashtable until the last row is
4430      unpacked. Then it scans the table to update and when a record in
4431      the table matches the one in the hashtable, the update/delete is
4432      performed.
4433    */
4434   int do_hash_scan_and_update(Relay_log_info const *rli);
4435 
4436   /**
4437      Implementation of the legacy table_scan and update algorithm. For
4438      each unpacked row it scans the storage engine table for a
4439      match. When a match is found, the update/delete operations are
4440      performed.
4441    */
4442   int do_table_scan_and_update(Relay_log_info const *rli);
4443 
4444   /**
4445     Initializes scanning of rows. Opens an index and initailizes an iterator
4446     over a list of distinct keys (m_distinct_keys) if it is a HASH_SCAN
4447     over an index or the table if its a HASH_SCAN over the table.
4448   */
4449   int open_record_scan();
4450 
4451   /**
4452     Does the cleanup
4453     - closes the index if opened by open_record_scan
4454     - closes the table if opened for scanning.
4455   */
4456   int close_record_scan();
4457 
4458   /**
4459     Fetches next row. If it is a HASH_SCAN over an index, it populates
4460     table->record[0] with the next row corresponding to the index. If
4461     the indexes are in non-contigous ranges it fetches record corresponding
4462     to the key value in the next range.
4463 
4464     @parms: bool first_read : signifying if this is the first time we are reading a row
4465             over an index.
4466     @return_value: -  error code when there are no more reeords to be fetched or some other
4467                       error occured,
4468                    -  0 otherwise.
4469   */
4470   int next_record_scan(bool first_read);
4471 
4472   /**
4473     Populates the m_distinct_keys with unique keys to be modified
4474     during HASH_SCAN over keys.
4475     @return_value -0 success
4476                   -Err_code
4477   */
4478   int add_key_to_distinct_keyset();
4479 
4480   /**
4481     Populates the m_hash when using HASH_SCAN. Thence, it:
4482     - unpacks the before image (BI)
4483     - saves the positions
4484     - saves the positions into the hash map, using the
4485       BI checksum as key
4486     - unpacks the after image (AI) if needed, so that
4487       m_curr_row_end gets updated correctly.
4488 
4489     @param rli The reference to the relay log info object.
4490     @returns 0 on success. Otherwise, the error code.
4491   */
4492   int do_hash_row(Relay_log_info const *rli);
4493 
4494   /**
4495     This member function scans the table and applies the changes
4496     that had been previously hashed. As such, m_hash MUST be filled
4497     by do_hash_row before calling this member function.
4498 
4499     @param rli The reference to the relay log info object.
4500     @returns 0 on success. Otherwise, the error code.
4501   */
4502   int do_scan_and_update(Relay_log_info const *rli);
4503 #endif /* defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) */
4504 
4505   friend class Old_rows_log_event;
4506 };
4507 
4508 /**
4509   @class Write_rows_log_event
4510 
4511   Log row insertions and updates. The event contain several
4512   insert/update rows for a table. Note that each event contains only
4513   rows for one table.
4514 
4515   @section Write_rows_log_event_binary_format Binary Format
4516 */
4517 class Write_rows_log_event : public Rows_log_event
4518 {
4519 public:
4520   enum
4521   {
4522     /* Support interface to THD::binlog_prepare_pending_rows_event */
4523     TYPE_CODE = WRITE_ROWS_EVENT
4524   };
4525 
4526 #if defined(MYSQL_SERVER)
4527   Write_rows_log_event(THD*, TABLE*, const Table_id& table_id,
4528 		       bool is_transactional,
4529                        const uchar* extra_row_info);
4530 #endif
4531 #ifdef HAVE_REPLICATION
4532   Write_rows_log_event(const char *buf, uint event_len,
4533                        const Format_description_log_event *description_event);
4534 #endif
4535 #if defined(MYSQL_SERVER)
binlog_row_logging_function(THD * thd,TABLE * table,bool is_transactional,const uchar * before_record MY_ATTRIBUTE ((unused)),const uchar * after_record)4536   static bool binlog_row_logging_function(THD *thd, TABLE *table,
4537                                           bool is_transactional,
4538                                           const uchar *before_record
4539                                           MY_ATTRIBUTE((unused)),
4540                                           const uchar *after_record)
4541   {
4542     return thd->binlog_write_row(table, is_transactional,
4543                                  after_record, NULL);
4544   }
4545 #endif
4546 
4547 protected:
4548   int write_row(const Relay_log_info *const, const bool);
4549 
4550 private:
get_general_type_code()4551   virtual Log_event_type get_general_type_code() { return (Log_event_type)TYPE_CODE; }
4552 
4553 #ifdef MYSQL_CLIENT
4554   void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
4555 #endif
4556 
4557 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4558   virtual int do_before_row_operations(const Slave_reporting_capability *const);
4559   virtual int do_after_row_operations(const Slave_reporting_capability *const,int);
4560   virtual int do_exec_row(const Relay_log_info *const);
4561 #endif
4562 };
4563 
4564 
4565 /**
4566   @class Update_rows_log_event
4567 
4568   Log row updates with a before image. The event contain several
4569   update rows for a table. Note that each event contains only rows for
4570   one table.
4571 
4572   Also note that the row data consists of pairs of row data: one row
4573   for the old data and one row for the new data.
4574 
4575   @section Update_rows_log_event_binary_format Binary Format
4576 */
4577 class Update_rows_log_event : public Rows_log_event
4578 {
4579 public:
4580   enum
4581   {
4582     /* Support interface to THD::binlog_prepare_pending_rows_event */
4583     TYPE_CODE = UPDATE_ROWS_EVENT
4584   };
4585 
4586 #ifdef MYSQL_SERVER
4587   Update_rows_log_event(THD*, TABLE*, const Table_id& table_id,
4588 			MY_BITMAP const *cols_bi,
4589 			MY_BITMAP const *cols_ai,
4590                         bool is_transactional,
4591                         const uchar* extra_row_info);
4592 
4593   Update_rows_log_event(THD*, TABLE*, const Table_id& table_id,
4594                         bool is_transactional,
4595                         const uchar* extra_row_info);
4596 
4597   void init(MY_BITMAP const *cols);
4598 #endif
4599 
4600   virtual ~Update_rows_log_event();
4601 
4602 #ifdef HAVE_REPLICATION
4603   Update_rows_log_event(const char *buf, uint event_len,
4604 			const Format_description_log_event *description_event);
4605 #endif
4606 
4607 #ifdef MYSQL_SERVER
binlog_row_logging_function(THD * thd,TABLE * table,bool is_transactional,const uchar * before_record,const uchar * after_record)4608   static bool binlog_row_logging_function(THD *thd, TABLE *table,
4609                                           bool is_transactional,
4610                                           const uchar *before_record,
4611                                           const uchar *after_record)
4612   {
4613     return thd->binlog_update_row(table, is_transactional,
4614                                   before_record, after_record, NULL);
4615   }
4616 #endif
4617 
is_valid()4618   virtual bool is_valid() const
4619   {
4620     return Rows_log_event::is_valid() && m_cols_ai.bitmap;
4621   }
4622 
4623 protected:
get_general_type_code()4624   virtual Log_event_type get_general_type_code() { return (Log_event_type)TYPE_CODE; }
4625 
4626 #ifdef MYSQL_CLIENT
4627   void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
4628 #endif
4629 
4630 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4631   virtual int do_before_row_operations(const Slave_reporting_capability *const);
4632   virtual int do_after_row_operations(const Slave_reporting_capability *const,int);
4633   virtual int do_exec_row(const Relay_log_info *const);
4634 #endif /* defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) */
4635 };
4636 
4637 /**
4638   @class Delete_rows_log_event
4639 
4640   Log row deletions. The event contain several delete rows for a
4641   table. Note that each event contains only rows for one table.
4642 
4643   RESPONSIBILITIES
4644 
4645     - Act as a container for rows that has been deleted on the master
4646       and should be deleted on the slave.
4647 
4648   COLLABORATION
4649 
4650     Row_writer
4651       Create the event and add rows to the event.
4652     Row_reader
4653       Extract the rows from the event.
4654 
4655   @section Delete_rows_log_event_binary_format Binary Format
4656 */
4657 class Delete_rows_log_event : public Rows_log_event
4658 {
4659 public:
4660   enum
4661   {
4662     /* Support interface to THD::binlog_prepare_pending_rows_event */
4663     TYPE_CODE = DELETE_ROWS_EVENT
4664   };
4665 
4666 #ifdef MYSQL_SERVER
4667   Delete_rows_log_event(THD*, TABLE*, const Table_id&,
4668 			bool is_transactional, const uchar* extra_row_info);
4669 #endif
4670 #ifdef HAVE_REPLICATION
4671   Delete_rows_log_event(const char *buf, uint event_len,
4672 			const Format_description_log_event *description_event);
4673 #endif
4674 #ifdef MYSQL_SERVER
binlog_row_logging_function(THD * thd,TABLE * table,bool is_transactional,const uchar * before_record,const uchar * after_record MY_ATTRIBUTE ((unused)))4675   static bool binlog_row_logging_function(THD *thd, TABLE *table,
4676                                           bool is_transactional,
4677                                           const uchar *before_record,
4678                                           const uchar *after_record
4679                                           MY_ATTRIBUTE((unused)))
4680   {
4681     return thd->binlog_delete_row(table, is_transactional,
4682                                   before_record, NULL);
4683   }
4684 #endif
4685 
4686 protected:
get_general_type_code()4687   virtual Log_event_type get_general_type_code() { return (Log_event_type)TYPE_CODE; }
4688 
4689 #ifdef MYSQL_CLIENT
4690   void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
4691 #endif
4692 
4693 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4694   virtual int do_before_row_operations(const Slave_reporting_capability *const);
4695   virtual int do_after_row_operations(const Slave_reporting_capability *const,int);
4696   virtual int do_exec_row(const Relay_log_info *const);
4697 #endif
4698 };
4699 
4700 
4701 #include "log_event_old.h"
4702 
4703 /**
4704   @class Incident_log_event
4705 
4706    Class representing an incident, an occurance out of the ordinary,
4707    that happened on the master.
4708 
4709    The event is used to inform the slave that something out of the
4710    ordinary happened on the master that might cause the database to be
4711    in an inconsistent state.
4712 
4713    <table id="IncidentFormat">
4714    <caption>Incident event format</caption>
4715    <tr>
4716      <th>Symbol</th>
4717      <th>Format</th>
4718      <th>Description</th>
4719    </tr>
4720    <tr>
4721      <td>INCIDENT</td>
4722      <td align="right">2</td>
4723      <td>Incident number as an unsigned integer</td>
4724    </tr>
4725    <tr>
4726      <td>MSGLEN</td>
4727      <td align="right">1</td>
4728      <td>Message length as an unsigned integer</td>
4729    </tr>
4730    <tr>
4731      <td>MESSAGE</td>
4732      <td align="right">MSGLEN</td>
4733      <td>The message, if present. Not null terminated.</td>
4734    </tr>
4735    </table>
4736 
4737   @section Delete_rows_log_event_binary_format Binary Format
4738 */
4739 class Incident_log_event : public Log_event {
4740 public:
4741 #ifdef MYSQL_SERVER
Incident_log_event(THD * thd_arg,Incident incident)4742   Incident_log_event(THD *thd_arg, Incident incident)
4743     : Log_event(thd_arg, LOG_EVENT_NO_FILTER_F, Log_event::EVENT_NO_CACHE,
4744                 Log_event::EVENT_IMMEDIATE_LOGGING), m_incident(incident)
4745   {
4746     DBUG_ENTER("Incident_log_event::Incident_log_event");
4747     DBUG_PRINT("enter", ("m_incident: %d", m_incident));
4748     m_message.str= NULL;                    /* Just as a precaution */
4749     m_message.length= 0;
4750     DBUG_VOID_RETURN;
4751   }
4752 
Incident_log_event(THD * thd_arg,Incident incident,LEX_STRING const msg)4753   Incident_log_event(THD *thd_arg, Incident incident, LEX_STRING const msg)
4754     : Log_event(thd_arg, LOG_EVENT_NO_FILTER_F,
4755                 Log_event::EVENT_NO_CACHE,
4756                 Log_event::EVENT_IMMEDIATE_LOGGING), m_incident(incident)
4757   {
4758     DBUG_ENTER("Incident_log_event::Incident_log_event");
4759     DBUG_PRINT("enter", ("m_incident: %d", m_incident));
4760     m_message.str= NULL;
4761     m_message.length= 0;
4762     if (!(m_message.str= (char*) my_malloc(msg.length+1, MYF(MY_WME))))
4763     {
4764       /* Mark this event invalid */
4765       m_incident= INCIDENT_NONE;
4766       DBUG_VOID_RETURN;
4767     }
4768     strmake(m_message.str, msg.str, msg.length);
4769     m_message.length= msg.length;
4770     DBUG_VOID_RETURN;
4771   }
4772 #endif
4773 
4774 #ifdef MYSQL_SERVER
4775   int pack_info(Protocol*);
4776 #endif
4777 
4778   Incident_log_event(const char *buf, uint event_len,
4779                      const Format_description_log_event *descr_event);
4780 
4781   virtual ~Incident_log_event();
4782 
4783 #ifdef MYSQL_CLIENT
4784   virtual void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
4785 #endif
4786 
4787 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4788   virtual int do_apply_event(Relay_log_info const *rli);
4789 #endif
4790 
4791   virtual bool write_data_header(IO_CACHE *file);
4792   virtual bool write_data_body(IO_CACHE *file);
4793 
get_type_code()4794   virtual Log_event_type get_type_code() { return INCIDENT_EVENT; }
4795 
is_valid()4796   virtual bool is_valid() const
4797   {
4798     return m_incident > INCIDENT_NONE && m_incident < INCIDENT_COUNT;
4799   }
get_data_size()4800   virtual int get_data_size() {
4801     return INCIDENT_HEADER_LEN + 1 + (uint) m_message.length;
4802   }
4803 
4804 private:
4805   const char *description() const;
4806 
4807   Incident m_incident;
4808   LEX_STRING m_message;
4809 };
4810 
4811 
4812 /**
4813   @class Ignorable_log_event
4814 
4815   Base class for ignorable log events. Events deriving from
4816   this class can be safely ignored by slaves that cannot
4817   recognize them. Newer slaves, will be able to read and
4818   handle them. This has been designed to be an open-ended
4819   architecture, so adding new derived events shall not harm
4820   the old slaves that support ignorable log event mechanism
4821   (they will just ignore unrecognized ignorable events).
4822 
4823   @note The only thing that makes an event ignorable is that it has
4824   the LOG_EVENT_IGNORABLE_F flag set.  It is not strictly necessary
4825   that ignorable event types derive from Ignorable_log_event; they may
4826   just as well derive from Log_event and pass LOG_EVENT_IGNORABLE_F as
4827   argument to the Log_event constructor.
4828 **/
4829 class Ignorable_log_event : public Log_event {
4830 public:
4831 #ifndef MYSQL_CLIENT
Ignorable_log_event(THD * thd_arg)4832   Ignorable_log_event(THD *thd_arg)
4833       : Log_event(thd_arg, LOG_EVENT_IGNORABLE_F,
4834                   Log_event::EVENT_STMT_CACHE,
4835                   Log_event::EVENT_NORMAL_LOGGING)
4836   {
4837     DBUG_ENTER("Ignorable_log_event::Ignorable_log_event");
4838     DBUG_VOID_RETURN;
4839   }
4840 #endif
4841 
4842   Ignorable_log_event(const char *buf,
4843                       const Format_description_log_event *descr_event);
4844   virtual ~Ignorable_log_event();
4845 
4846 #ifndef MYSQL_CLIENT
4847   int pack_info(Protocol*);
4848 #endif
4849 
4850 #ifdef MYSQL_CLIENT
4851   virtual void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
4852 #endif
4853 
get_type_code()4854   virtual Log_event_type get_type_code() { return IGNORABLE_LOG_EVENT; }
4855 
is_valid()4856   virtual bool is_valid() const { return 1; }
4857 
get_data_size()4858   virtual int get_data_size() { return IGNORABLE_HEADER_LEN; }
4859 };
4860 
4861 
4862 class Rows_query_log_event : public Ignorable_log_event {
4863 public:
4864 #ifndef MYSQL_CLIENT
Rows_query_log_event(THD * thd_arg,const char * query,ulong query_len)4865   Rows_query_log_event(THD *thd_arg, const char * query, ulong query_len)
4866     : Ignorable_log_event(thd_arg)
4867   {
4868     DBUG_ENTER("Rows_query_log_event::Rows_query_log_event");
4869     if (!(m_rows_query= (char*) my_malloc(query_len + 1, MYF(MY_WME))))
4870       return;
4871     my_snprintf(m_rows_query, query_len + 1, "%s", query);
4872     DBUG_PRINT("enter", ("%s", m_rows_query));
4873     DBUG_VOID_RETURN;
4874   }
4875 #endif
4876 
4877 #ifndef MYSQL_CLIENT
4878   int pack_info(Protocol*);
4879 #endif
4880 
4881   Rows_query_log_event(const char *buf, uint event_len,
4882                      const Format_description_log_event *descr_event);
4883 
4884   virtual ~Rows_query_log_event();
4885 
4886 #ifdef MYSQL_CLIENT
4887   virtual void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
4888 #endif
4889   virtual bool write_data_body(IO_CACHE *file);
4890 
get_type_code()4891   virtual Log_event_type get_type_code() { return ROWS_QUERY_LOG_EVENT; }
4892 
is_valid()4893   virtual bool is_valid() const { return m_rows_query != NULL; }
4894 
get_data_size()4895   virtual int get_data_size()
4896   {
4897     return IGNORABLE_HEADER_LEN + 1 + (uint) strlen(m_rows_query);
4898   }
4899 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
4900   virtual int do_apply_event(Relay_log_info const *rli);
4901 #endif
4902 
4903 private:
4904 
4905   char * m_rows_query;
4906 };
4907 
4908 
4909 
copy_event_cache_to_file_and_reinit(IO_CACHE * cache,FILE * file,bool flush_stream)4910 static inline bool copy_event_cache_to_file_and_reinit(IO_CACHE *cache,
4911                                                        FILE *file,
4912                                                        bool flush_stream)
4913 {
4914   return
4915     my_b_copy_to_file(cache, file) ||
4916     (flush_stream ? (fflush(file) || ferror(file)) : 0) ||
4917     reinit_io_cache(cache, WRITE_CACHE, 0, FALSE, TRUE);
4918 }
4919 
4920 #ifdef MYSQL_SERVER
4921 /*****************************************************************************
4922 
4923   Heartbeat Log Event class
4924 
4925   Replication event to ensure to slave that master is alive.
4926   The event is originated by master's dump thread and sent straight to
4927   slave without being logged. Slave itself does not store it in relay log
4928   but rather uses a data for immediate checks and throws away the event.
4929 
4930   Two members of the class log_ident and Log_event::log_pos comprise
4931   @see the event_coordinates instance. The coordinates that a heartbeat
4932   instance carries correspond to the last event master has sent from
4933   its binlog.
4934 
4935  ****************************************************************************/
4936 class Heartbeat_log_event: public Log_event
4937 {
4938 public:
4939   Heartbeat_log_event(const char* buf, uint event_len,
4940                       const Format_description_log_event* description_event);
get_type_code()4941   Log_event_type get_type_code() { return HEARTBEAT_LOG_EVENT; }
is_valid()4942   bool is_valid() const
4943     {
4944       return (log_ident != NULL &&
4945               log_pos >= BIN_LOG_HEADER_SIZE);
4946     }
get_log_ident()4947   const char * get_log_ident() { return log_ident; }
get_ident_len()4948   uint get_ident_len() { return ident_len; }
4949 
4950 private:
4951   const char* log_ident;
4952   uint ident_len;
4953 };
4954 
4955 /**
4956    The function is called by slave applier in case there are
4957    active table filtering rules to force gathering events associated
4958    with Query-log-event into an array to execute
4959    them once the fate of the Query is determined for execution.
4960 */
4961 bool slave_execute_deferred_events(THD *thd);
4962 #endif
4963 
4964 int append_query_string(THD *thd, const CHARSET_INFO *csinfo,
4965                         String const *from, String *to);
4966 bool event_checksum_test(uchar *buf, ulong event_len, uint8 alg);
4967 uint8 get_checksum_alg(const char* buf, ulong len);
4968 extern TYPELIB binlog_checksum_typelib;
4969 
4970 class Gtid_log_event : public Log_event
4971 {
4972 public:
4973 #ifndef MYSQL_CLIENT
4974   /**
4975     Create a new event using the GTID from the given Gtid_specification,
4976     or from @@SESSION.GTID_NEXT if spec==NULL.
4977   */
4978   Gtid_log_event(THD *thd_arg, bool using_trans,
4979                  const Gtid_specification *spec= NULL);
4980 #endif
4981 
4982 #ifndef MYSQL_CLIENT
4983   int pack_info(Protocol*);
4984 #endif
4985 
4986   Gtid_log_event(const char *buffer, uint event_len,
4987                  const Format_description_log_event *descr_event);
4988 
~Gtid_log_event()4989   virtual ~Gtid_log_event() {}
4990 
get_type_code()4991   Log_event_type get_type_code()
4992   {
4993     DBUG_ENTER("Gtid_log_event::get_type_code()");
4994     Log_event_type ret= (spec.type == ANONYMOUS_GROUP ?
4995                          ANONYMOUS_GTID_LOG_EVENT : GTID_LOG_EVENT);
4996     DBUG_PRINT("info", ("code=%d=%s", ret, get_type_str(ret)));
4997     DBUG_RETURN(ret);
4998   }
4999 
get_data_size()5000   int get_data_size() { return POST_HEADER_LENGTH; }
5001 
5002 private:
5003   /// Used internally by both print() and pack_info().
5004   size_t to_string(char *buf) const;
5005 
5006 public:
5007 #ifdef MYSQL_CLIENT
5008   void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
5009 #endif
5010 #ifdef MYSQL_SERVER
5011   bool write_data_header(IO_CACHE *file);
5012 #endif
5013 
5014 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
5015   int do_apply_event(Relay_log_info const *rli);
5016   int do_update_pos(Relay_log_info *rli);
5017 #endif
5018 
5019   /**
5020     Return the group type for this Gtid_log_event: this can be
5021     either ANONYMOUS_GROUP, AUTOMATIC_GROUP, or GTID_GROUP.
5022   */
get_type()5023   enum_group_type get_type() const { return spec.type; }
is_valid()5024   bool is_valid() const { return true; }
5025 
5026   /**
5027     Return the SID for this GTID.  The SID is shared with the
5028     Log_event so it should not be modified.
5029   */
get_sid()5030   const rpl_sid* get_sid() const { return &sid; }
5031   /**
5032     Return the SIDNO relative to the global sid_map for this GTID.
5033 
5034     This requires a lookup and possibly even update of global_sid_map,
5035     hence global_sid_lock must be held.  If global_sid_lock is not
5036     held, the caller must pass need_lock=true.  If there is an error
5037     (e.g. out of memory) while updating global_sid_map, this function
5038     returns a negative number.
5039 
5040     @param need_lock If true, the read lock on global_sid_lock is
5041     acquired and released inside this function; if false, the read
5042     lock or write lock must be held prior to calling this function.
5043     @retval SIDNO if successful
5044     @retval negative if adding SID to global_sid_map causes an error.
5045   */
get_sidno(bool need_lock)5046   rpl_sidno get_sidno(bool need_lock)
5047   {
5048     if (spec.gtid.sidno < 0)
5049     {
5050       if (need_lock)
5051         global_sid_lock->rdlock();
5052       else
5053         global_sid_lock->assert_some_lock();
5054       spec.gtid.sidno= global_sid_map->add_sid(sid);
5055       if (need_lock)
5056         global_sid_lock->unlock();
5057     }
5058     return spec.gtid.sidno;
5059   }
5060   /**
5061     Return the SIDNO relative to the given Sid_map for this GTID.
5062 
5063     This assumes that the Sid_map is local to the thread, and thus
5064     does not use locks.
5065 
5066     @param sid_map The sid_map to use.
5067     @retval SIDNO if successful.
5068     @negative if adding SID to sid_map causes an error.
5069   */
get_sidno(Sid_map * sid_map)5070   rpl_sidno get_sidno(Sid_map *sid_map)
5071   {
5072     return sid_map->add_sid(sid);
5073   }
5074   /// Return the GNO for this GTID.
get_gno()5075   rpl_gno get_gno() const { return spec.gtid.gno; }
5076   /// Return true if this is the last group of the transaction, else false.
get_commit_flag()5077   bool get_commit_flag() const { return commit_flag; }
5078 
5079   /// string holding the text "SET @@GLOBAL.GTID_NEXT = '"
5080   static const char *SET_STRING_PREFIX;
5081 private:
5082   /// Length of SET_STRING_PREFIX
5083   static const size_t SET_STRING_PREFIX_LENGTH= 26;
5084   /// The maximal length of the entire "SET ..." query.
5085   static const size_t MAX_SET_STRING_LENGTH= SET_STRING_PREFIX_LENGTH +
5086     rpl_sid::TEXT_LENGTH + 1 + MAX_GNO_TEXT_LENGTH + 1;
5087 
5088   /// Length of the commit_flag in event encoding
5089   static const int ENCODED_FLAG_LENGTH= 1;
5090   /// Length of SID in event encoding
5091   static const int ENCODED_SID_LENGTH= rpl_sid::BYTE_LENGTH;
5092   /// Length of GNO in event encoding
5093   static const int ENCODED_GNO_LENGTH= 8;
5094 
5095 public:
5096   /// Total length of post header
5097   static const int POST_HEADER_LENGTH=
5098     ENCODED_FLAG_LENGTH + ENCODED_SID_LENGTH + ENCODED_GNO_LENGTH;
5099 
5100 private:
5101   /**
5102     Internal representation of the GTID.  The SIDNO will be
5103     uninitialized (value -1) until the first call to get_sidno(bool).
5104   */
5105   Gtid_specification spec;
5106   /// SID for this GTID.
5107   rpl_sid sid;
5108   /// True if this is the last group of the transaction, false otherwise.
5109   bool commit_flag;
5110 };
5111 
5112 
5113 class Previous_gtids_log_event : public Log_event
5114 {
5115 public:
5116 #ifndef MYSQL_CLIENT
5117   Previous_gtids_log_event(const Gtid_set *set);
5118 #endif
5119 
5120 #ifndef MYSQL_CLIENT
5121   int pack_info(Protocol*);
5122 #endif
5123 
5124   Previous_gtids_log_event(const char *buffer, uint event_len,
5125                            const Format_description_log_event *descr_event);
~Previous_gtids_log_event()5126   virtual ~Previous_gtids_log_event() {}
5127 
get_type_code()5128   Log_event_type get_type_code() { return PREVIOUS_GTIDS_LOG_EVENT; }
5129 
is_valid()5130   bool is_valid() const { return buf != NULL; }
get_data_size()5131   int get_data_size() { return buf_size; }
5132 
5133 #ifdef MYSQL_CLIENT
5134   void print(FILE *file, PRINT_EVENT_INFO *print_event_info);
5135 #endif
5136 #ifdef MYSQL_SERVER
write(IO_CACHE * file)5137   bool write(IO_CACHE* file)
5138   {
5139     if (DBUG_EVALUATE_IF("skip_writing_previous_gtids_log_event", 1, 0))
5140     {
5141       DBUG_PRINT("info", ("skip writing Previous_gtids_log_event because of debug option 'skip_writing_previous_gtids_log_event'"));
5142       return false;
5143     }
5144 
5145     if (DBUG_EVALUATE_IF("write_partial_previous_gtids_log_event", 1, 0))
5146     {
5147       DBUG_PRINT("info", ("writing partial Previous_gtids_log_event because of debug option 'write_partial_previous_gtids_log_event'"));
5148       return (Log_event::write_header(file, get_data_size()) ||
5149               Log_event::write_data_header(file));
5150     }
5151 
5152     return (Log_event::write_header(file, get_data_size()) ||
5153             Log_event::write_data_header(file) ||
5154             write_data_body(file) ||
5155             Log_event::write_footer(file));
5156   }
5157   bool write_data_body(IO_CACHE *file);
5158 #endif
5159 
5160   /// Return the encoded buffer, or NULL on error.
get_buf()5161   const uchar *get_buf() { return buf; }
5162   /**
5163     Return the formatted string, or NULL on error.
5164 
5165     The string is allocated using my_malloc and it is the
5166     responsibility of the caller to free it.
5167   */
5168   char *get_str(size_t *length,
5169                 const Gtid_set::String_format *string_format) const;
5170   /// Add all GTIDs from this event to the given Gtid_set.
5171   int add_to_set(Gtid_set *gtid_set) const;
5172   /*
5173     Previous Gtid Log events should always be skipped
5174     there is nothing to apply there, whether it is
5175     relay log's (generated on Slave) or it is binary log's
5176     (generated on Master, copied to slave as relay log).
5177     Also, we should not increment slave_skip_counter
5178     for this event, hence return EVENT_SKIP_IGNORE.
5179    */
do_shall_skip(Relay_log_info * rli)5180   enum_skip_reason do_shall_skip(Relay_log_info *rli)
5181   {
5182     return EVENT_SKIP_IGNORE;
5183   }
5184 
5185 #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION)
do_apply_event(Relay_log_info const * rli)5186   int do_apply_event(Relay_log_info const *rli) { return 0; }
5187   int do_update_pos(Relay_log_info *rli);
5188 #endif
5189 
5190 private:
5191   int buf_size;
5192   const uchar *buf;
5193 };
5194 
is_gtid_event(Log_event * evt)5195 inline bool is_gtid_event(Log_event* evt)
5196 {
5197   return (evt->get_type_code() == GTID_LOG_EVENT ||
5198           evt->get_type_code() == ANONYMOUS_GTID_LOG_EVENT);
5199 }
5200 
version_product(const uchar * version_split)5201 inline ulong version_product(const uchar* version_split)
5202 {
5203   return ((version_split[0] * 256 + version_split[1]) * 256
5204           + version_split[2]);
5205 }
5206 
5207 /**
5208    Splits server 'version' string into three numeric pieces stored
5209    into 'split_versions':
5210    X.Y.Zabc (X,Y,Z numbers, a not a digit) -> {X,Y,Z}
5211    X.Yabc -> {X,Y,0}
5212 */
do_server_version_split(char * version,uchar split_versions[3])5213 inline void do_server_version_split(char* version, uchar split_versions[3])
5214 {
5215   char *p= version, *r;
5216   ulong number;
5217   for (uint i= 0; i<=2; i++)
5218   {
5219     number= strtoul(p, &r, 10);
5220     /*
5221       It is an invalid version if any version number greater than 255 or
5222       first number is not followed by '.'.
5223     */
5224     if (number < 256 && (*r == '.' || i != 0))
5225       split_versions[i]= (uchar)number;
5226     else
5227     {
5228       split_versions[0]= 0;
5229       split_versions[1]= 0;
5230       split_versions[2]= 0;
5231       break;
5232     }
5233 
5234     p= r;
5235     if (*r == '.')
5236       p++; // skip the dot
5237   }
5238 }
5239 
5240 #ifdef MYSQL_SERVER
5241 /*
5242   This is an utility function that adds a quoted identifier into the a buffer.
5243   This also escapes any existance of the quote string inside the identifier.
5244  */
5245 size_t my_strmov_quoted_identifier(THD *thd, char *buffer,
5246                                    const char* identifier,
5247                                    uint length);
5248 #else
5249 size_t my_strmov_quoted_identifier(char *buffer, const char* identifier);
5250 #endif
5251 size_t my_strmov_quoted_identifier_helper(int q, char *buffer,
5252                                           const char* identifier,
5253                                           uint length);
5254 
5255 /**
5256   @} (end of group Replication)
5257 */
5258 
5259 #endif /* _log_event_h */
5260