Skip to main content

binlog_inspect/
event.rs

1// Copyright (c) 2026 houseme
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stable output model, independent of the underlying binlog library.
5use serde::{Deserialize, Serialize};
6
7/// Canonical event type; the single source of truth for event naming.
8///
9/// The JSON output renders the snake_case variant name, which matches the
10/// historical string values byte for byte.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
13#[serde(rename_all = "snake_case")]
14#[cfg_attr(feature = "cli", value(rename_all = "snake_case"))]
15pub enum EventType {
16    /// Layout description for the rest of the binlog file.
17    FormatDescription,
18    /// Table identifier and its schema.
19    TableMap,
20    /// Inserted row images.
21    WriteRows,
22    /// Updated row image pairs.
23    UpdateRows,
24    /// Deleted row images.
25    DeleteRows,
26    /// Partial update row events: only before images are full row images,
27    /// after images are JSON diffs that are not decoded.
28    PartialUpdateRows,
29    /// Statement event.
30    Query,
31    /// Transaction commit identifier.
32    Xid,
33    /// Global transaction identifier (tagged or untagged).
34    Gtid,
35    /// Global transaction identifier of an anonymous transaction.
36    AnonymousGtid,
37    /// GTID set committed before the current binlog file.
38    PreviousGtids,
39    /// Log rotation.
40    Rotate,
41    /// Server shutdown marker.
42    Stop,
43    /// Original statement for row events.
44    RowsQuery,
45    /// Replication incident report.
46    Incident,
47    /// Statement-time integer variable assignment.
48    Intvar,
49    /// Random seed used by statement-based replication.
50    Rand,
51    /// User-defined variable assignment.
52    UserVar,
53    /// Bulk load data carried outside the statement stream.
54    BeginLoadQuery,
55    /// Bulk load execution marker.
56    ExecuteLoadQuery,
57    /// Replication heartbeat.
58    Heartbeat,
59    /// Event that may be safely ignored by readers that do not handle it.
60    Ignorable,
61    /// Two-phase commit transaction context.
62    TransactionContext,
63    /// Group replication view change.
64    ViewChange,
65    /// XA transaction prepare.
66    XaPrepare,
67    /// Compressed transaction payload (WL#3549) enclosing a whole transaction.
68    TransactionPayload,
69    /// Event type that this version does not name.
70    Unknown,
71}
72
73impl EventType {
74    /// The snake_case name used in JSON output; identical to the serde
75    /// rendering of this variant.
76    pub fn as_str(self) -> &'static str {
77        match self {
78            Self::FormatDescription => "format_description",
79            Self::TableMap => "table_map",
80            Self::WriteRows => "write_rows",
81            Self::UpdateRows => "update_rows",
82            Self::DeleteRows => "delete_rows",
83            Self::PartialUpdateRows => "partial_update_rows",
84            Self::Query => "query",
85            Self::Xid => "xid",
86            Self::Gtid => "gtid",
87            Self::AnonymousGtid => "anonymous_gtid",
88            Self::PreviousGtids => "previous_gtids",
89            Self::Rotate => "rotate",
90            Self::Stop => "stop",
91            Self::RowsQuery => "rows_query",
92            Self::Incident => "incident",
93            Self::Intvar => "intvar",
94            Self::Rand => "rand",
95            Self::UserVar => "user_var",
96            Self::BeginLoadQuery => "begin_load_query",
97            Self::ExecuteLoadQuery => "execute_load_query",
98            Self::Heartbeat => "heartbeat",
99            Self::Ignorable => "ignorable",
100            Self::TransactionContext => "transaction_context",
101            Self::ViewChange => "view_change",
102            Self::XaPrepare => "xa_prepare",
103            Self::TransactionPayload => "transaction_payload",
104            Self::Unknown => "unknown",
105        }
106    }
107
108    /// Maps a raw binlog event type number to the canonical event type.
109    ///
110    /// Pre-GA row events (codes 23-25) and MariaDB-only codes (160+) have no
111    /// stable cross-server meaning and are reported as [`EventType::Unknown`].
112    pub fn from_raw(code: u8) -> Self {
113        match code {
114            2 => Self::Query,
115            3 => Self::Stop,
116            4 => Self::Rotate,
117            5 => Self::Intvar,
118            13 => Self::Rand,
119            14 => Self::UserVar,
120            15 => Self::FormatDescription,
121            16 => Self::Xid,
122            17 => Self::BeginLoadQuery,
123            18 => Self::ExecuteLoadQuery,
124            19 => Self::TableMap,
125            26 => Self::Incident,
126            27 | 41 => Self::Heartbeat,
127            28 => Self::Ignorable,
128            29 => Self::RowsQuery,
129            30 => Self::WriteRows,
130            31 => Self::UpdateRows,
131            32 => Self::DeleteRows,
132            33 | 42 => Self::Gtid,
133            34 => Self::AnonymousGtid,
134            35 => Self::PreviousGtids,
135            36 => Self::TransactionContext,
136            37 => Self::ViewChange,
137            38 => Self::XaPrepare,
138            39 => Self::PartialUpdateRows,
139            40 => Self::TransactionPayload,
140            _ => Self::Unknown,
141        }
142    }
143}
144
145impl std::fmt::Display for EventType {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        f.write_str(self.as_str())
148    }
149}
150
151/// An event and its byte offset in the input file.
152#[derive(Debug, PartialEq, Serialize, Deserialize)]
153pub struct ParsedEvent {
154    /// File offset of the event header.
155    pub offset: u64,
156    /// Unix timestamp in seconds.
157    pub timestamp: u32,
158    /// Canonical event type.
159    pub event_type: EventType,
160    /// Raw MySQL event type number.
161    pub event_type_code: u8,
162    /// Originating server ID.
163    pub server_id: u32,
164    /// Event size including header.
165    pub event_size: u32,
166    /// Position of the next event recorded in the header.
167    pub log_pos: u32,
168    /// Decoded event content.
169    pub payload: EventPayload,
170}
171
172/// Event-specific content.
173#[derive(Debug, PartialEq, Serialize, Deserialize)]
174#[serde(tag = "kind", rename_all = "snake_case")]
175pub enum EventPayload {
176    /// Format description.
177    FormatDescription {
178        /// Server version with NUL padding removed.
179        server_version: String,
180    },
181    /// Table identifier and its schema.
182    TableMap {
183        /// Table identifier used by following row events.
184        table_id: u64,
185        /// Database containing the table.
186        database: String,
187        /// Table name.
188        table: String,
189        /// Number of columns in the table.
190        column_count: u64,
191    },
192    /// Row images with typed column values.
193    Rows {
194        /// Table identifier from the preceding table map event.
195        table_id: u64,
196        /// Database containing the table.
197        database: String,
198        /// Table name.
199        table: String,
200        /// One entry per affected row.
201        changes: Vec<RowChange>,
202    },
203    /// Partial update row event (WL#2955).
204    ///
205    /// The before image is a full row image. The after image is a sequence of
206    /// JSON diffs per JSON column, which is applied against the before value:
207    /// an applied column renders as [`CellValue::Json`] with the full new
208    /// document, and a diff that cannot be applied renders as
209    /// [`CellValue::PartialJson`] with the preserved diffs and the reason.
210    PartialUpdateRows {
211        /// Table identifier from the preceding table map event.
212        table_id: u64,
213        /// Database containing the table.
214        database: String,
215        /// Table name.
216        table: String,
217        /// Full before image per affected row; `None` when the image is absent.
218        before: Vec<Option<RowImage>>,
219        /// After image per affected row with diffs applied; `None` when the
220        /// image is absent.
221        after: Vec<Option<RowImage>>,
222    },
223    /// A row event whose table map was not available.
224    Unresolved {
225        /// Table identifier that had no table map event.
226        table_id: u64,
227    },
228    /// Statement event.
229    Query {
230        /// Default database of the statement.
231        database: String,
232        /// Statement text.
233        sql: String,
234    },
235    /// Transaction commit identifier.
236    Xid {
237        /// Transaction ID.
238        xid: u64,
239    },
240    /// Global transaction identifier.
241    Gtid {
242        /// Canonical GTID: `uuid:gno` when untagged, `uuid:tag:gno` when
243        /// tagged; `ANONYMOUS` for anonymous transactions.
244        gtid: String,
245        /// GTID tag (MySQL 8.4+), if present.
246        tag: Option<String>,
247    },
248    /// GTID set committed before the current binlog file, rendered in the
249    /// mysqlbinlog textual form (`uuid[:tag]:interval[,...]`, sids separated
250    /// by commas).
251    PreviousGtids {
252        /// Rendered GTID set.
253        gtid_set: String,
254    },
255    /// Log rotation.
256    Rotate {
257        /// Name of the next binlog file.
258        next_file: String,
259        /// Start position in the next file.
260        position: u64,
261    },
262    /// Server shutdown marker.
263    Stop,
264    /// Original statement for row events.
265    RowsQuery {
266        /// Statement text.
267        sql: String,
268    },
269    /// Replication incident report.
270    Incident {
271        /// Canonical incident type name, or `UNKNOWN(n)` for unrecognized codes.
272        incident_type: String,
273        /// Human-readable incident description.
274        message: String,
275    },
276    /// Statement-time integer variable assignment.
277    Intvar {
278        /// Variable kind, using the library's stable constant names
279        /// (`INVALID_INT_EVENT`, `LAST_INSERT_ID_EVENT`, `INSERT_ID_EVENT`).
280        var_type: String,
281        /// Assigned value.
282        value: u64,
283    },
284    /// Unhandled event, retained with its type and size.
285    Unknown {
286        /// Length of the retained event data.
287        raw_len: usize,
288    },
289    /// A compressed transaction payload (code 40, WL#3549) and its decoded
290    /// inner events.
291    ///
292    /// The compression algorithm byte is validated before the underlying
293    /// library parses the header, the payload is only ever streamed through a
294    /// counting decompression reader bounded by the declared size, and inner
295    /// events share the parser's table map state with the outer stream.
296    TransactionPayload {
297        /// Canonical compression name: `"NONE"` or `"ZSTD"`.
298        compression: String,
299        /// Declared uncompressed size from the payload header.
300        uncompressed_size: u64,
301        /// Inner events in stream order; the `offset` of each inner event is
302        /// its byte position inside the decompressed payload, while
303        /// `timestamp` and `server_id` are inherited from the enclosing event.
304        events: Vec<ParsedEvent>,
305    },
306}
307
308/// Before and after images for a single row.
309#[derive(Debug, PartialEq, Serialize, Deserialize)]
310pub struct RowChange {
311    /// Previous image, if present.
312    pub before: Option<RowImage>,
313    /// New image, if present.
314    pub after: Option<RowImage>,
315}
316
317/// A row image in table-column order, including columns omitted by minimal row images.
318#[derive(Debug, PartialEq, Serialize, Deserialize)]
319pub struct RowImage {
320    /// Cells are in zero-based table-column order.
321    pub columns: Vec<ColumnValue>,
322}
323
324/// One table column in a row image.
325#[derive(Debug, PartialEq, Serialize, Deserialize)]
326pub struct ColumnValue {
327    /// Zero-based position in the table.
328    pub index: usize,
329    /// Column name when present in binlog metadata; otherwise a generated name.
330    pub name: Option<String>,
331    /// MySQL column type, if this column is present in the row image.
332    pub mysql_type: Option<String>,
333    /// Signedness metadata for numeric columns; unknown if the binlog omitted it.
334    pub signedness: Option<Signedness>,
335    /// Value, including explicit absent and SQL NULL states.
336    pub value: CellValue,
337}
338
339/// Loss-aware MySQL value representation.
340///
341/// When deserializing, [`CellValue::Bytes`] expects the lowercase hexadecimal
342/// encoding produced by serialization; no character decoding is performed.
343#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
344#[serde(tag = "type", content = "value", rename_all = "snake_case")]
345pub enum CellValue {
346    /// Column omitted from this image.
347    Absent,
348    /// SQL NULL.
349    Null,
350    /// Bytes encoded as lowercase hexadecimal; no character encoding is assumed.
351    Bytes(String),
352    /// Signed integer.
353    Int(i64),
354    /// Unsigned integer.
355    UInt(u64),
356    /// Single-precision value, rendered as a string to preserve non-finite values.
357    Float(String),
358    /// Double-precision value, rendered as a string to preserve non-finite values.
359    Double(String),
360    /// Date or datetime components, including zero dates.
361    Date {
362        /// Gregorian year.
363        year: u16,
364        /// Month of the year (1-12).
365        month: u8,
366        /// Day of the month (1-31).
367        day: u8,
368        /// Hour of the day (0-23).
369        hour: u8,
370        /// Minute of the hour (0-59).
371        minute: u8,
372        /// Second of the minute (0-59).
373        second: u8,
374        /// Microsecond component.
375        micros: u32,
376    },
377    /// Signed MySQL TIME components, including values greater than 24 hours.
378    Time {
379        /// Whether the value is negative.
380        negative: bool,
381        /// Whole days beyond the hour component.
382        days: u32,
383        /// Remaining hours (0-23).
384        hours: u8,
385        /// Remaining minutes (0-59).
386        minutes: u8,
387        /// Remaining seconds (0-59).
388        seconds: u8,
389        /// Microsecond component.
390        micros: u32,
391    },
392    /// Decoded full JSON value.
393    Json(serde_json::Value),
394    /// JSON column whose after image is a sequence of binlog JSON diffs that
395    /// could not be applied to a before value; the raw diffs are preserved.
396    ///
397    /// A successful diff application renders as [`CellValue::Json`]; this
398    /// variant records the loss and why it happened.
399    PartialJson {
400        /// The recorded diffs in stream order.
401        diffs: Vec<JsonDiffRecord>,
402        /// Why the diffs could not be applied to the before value.
403        reason: String,
404    },
405}
406
407/// One recorded JSON diff of a partial JSON update (WL#2955).
408///
409/// Binlog JSON diffs describe a logical change to a JSON document; the `path`
410/// uses the MySQL JSON path text form (for example `$.a[2]`).
411#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
412#[serde(rename_all = "snake_case")]
413pub struct JsonDiffRecord {
414    /// MySQL JSON path of the change.
415    pub path: String,
416    /// Operation name: `"replace"`, `"insert"`, or `"remove"`.
417    pub operation: String,
418    /// New value carried by replace and insert operations; remove carries none.
419    pub value: Option<serde_json::Value>,
420}
421
422/// Signedness carried by the table map, or unknown when metadata was omitted.
423#[derive(Debug, PartialEq, Serialize, Deserialize)]
424#[serde(rename_all = "snake_case")]
425pub enum Signedness {
426    /// A signed numeric column.
427    Signed,
428    /// An unsigned numeric column.
429    Unsigned,
430    /// Decoded using the library's signed default; schema is required to interpret it.
431    Unknown,
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437
438    #[test]
439    fn as_str_matches_serde_snake_case() {
440        let codes = [
441            0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
442            24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 100,
443            160, 255,
444        ];
445        for code in codes {
446            let event_type = EventType::from_raw(code);
447            let json = serde_json::to_string(&event_type).unwrap();
448            assert_eq!(
449                json.trim_matches('"'),
450                event_type.as_str(),
451                "serde and as_str disagree for code {code}"
452            );
453        }
454    }
455
456    #[test]
457    fn raw_code_table_matches_contract() {
458        let expected = [
459            (2u8, "query"),
460            (3, "stop"),
461            (4, "rotate"),
462            (5, "intvar"),
463            (13, "rand"),
464            (14, "user_var"),
465            (15, "format_description"),
466            (16, "xid"),
467            (17, "begin_load_query"),
468            (18, "execute_load_query"),
469            (19, "table_map"),
470            (26, "incident"),
471            (27, "heartbeat"),
472            (28, "ignorable"),
473            (29, "rows_query"),
474            (30, "write_rows"),
475            (31, "update_rows"),
476            (32, "delete_rows"),
477            (33, "gtid"),
478            (34, "anonymous_gtid"),
479            (35, "previous_gtids"),
480            (36, "transaction_context"),
481            (37, "view_change"),
482            (38, "xa_prepare"),
483            (39, "partial_update_rows"),
484            (40, "transaction_payload"),
485            (41, "heartbeat"),
486            (42, "gtid"),
487        ];
488        for (code, name) in expected {
489            assert_eq!(EventType::from_raw(code).as_str(), name, "code {code}");
490        }
491        for code in [
492            0u8, 1, 6, 7, 8, 9, 10, 11, 12, 20, 21, 22, 23, 24, 25, 43, 160, 255,
493        ] {
494            assert_eq!(EventType::from_raw(code), EventType::Unknown, "code {code}");
495        }
496    }
497}