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