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