Skip to main content

mysql_replication/events/
rows.rs

1use super::Event;
2use crate::{Result, error::invalid, wire::Cursor};
3use std::io::Write;
4
5/// Protocol operation, independent from a CDC change or table whitelist.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum RowsKind {
8    Write,
9    Update,
10    Delete,
11}
12
13#[derive(Debug, Clone, Copy)]
14pub struct TableMapEvent<'a> {
15    pub table_id: u64,
16    pub flags: u16,
17    pub schema: &'a [u8],
18    pub table: &'a [u8],
19    /// Column types, per-type metadata, nullability and optional metadata.
20    /// Kept encoded so excluded tables need no column-plan allocation.
21    pub column_data: &'a [u8],
22    pub(crate) post_header: usize,
23}
24impl Default for TableMapEvent<'_> {
25    fn default() -> Self {
26        Self::with_post_header(8)
27    }
28}
29impl TableMapEvent<'_> {
30    pub fn with_post_header(post_header: usize) -> Self {
31        Self {
32            table_id: 0,
33            flags: 0,
34            schema: &[],
35            table: &[],
36            column_data: &[],
37            post_header,
38        }
39    }
40    /// Validates column envelopes only when a consumer needs this table.
41    pub fn columns(&self) -> Result<TableColumns<'_>> {
42        let mut input = Cursor::new(self.column_data);
43        let count = input.lenenc()?;
44        if count == 0 || count > 4096 {
45            return Err(invalid("TABLE_MAP column count outside 1..4096"));
46        }
47        let types = input.take(count)?;
48        let metadata_len = input.lenenc()?;
49        let metadata = input.take(metadata_len)?;
50        let nullable = input.take(count.div_ceil(8))?;
51        Ok(TableColumns {
52            count,
53            types,
54            metadata,
55            nullable,
56            optional_metadata: input.remaining(),
57        })
58    }
59}
60#[derive(Debug, Clone, Copy)]
61pub struct TableColumns<'a> {
62    pub count: usize,
63    pub types: &'a [u8],
64    pub metadata: &'a [u8],
65    pub nullable: &'a [u8],
66    pub optional_metadata: &'a [u8],
67}
68impl<'a> Event<'a> for TableMapEvent<'a> {
69    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
70        writeln!(writer, "Table ID: {}", self.table_id)?;
71        writeln!(writer, "Flags: {}", self.flags)?;
72        writeln!(writer, "Schema: {}", String::from_utf8_lossy(self.schema))?;
73        writeln!(writer, "Table: {}", String::from_utf8_lossy(self.table))?;
74        writeln!(writer, "Column data: {:02x?}", self.column_data)?;
75        writeln!(writer)?;
76        Ok(())
77    }
78
79    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
80        let width = match self.post_header {
81            6 => 4,
82            8 => 6,
83            _ => return Err(invalid("unsupported TABLE_MAP post-header")),
84        };
85        let mut input = Cursor::new(data);
86        let table_id = input.le(width)?;
87        let flags = input.le(2)? as u16;
88        let schema = input.name()?;
89        let table = input.name()?;
90        *self = Self {
91            table_id,
92            flags,
93            schema,
94            table,
95            column_data: input.remaining(),
96            post_header: self.post_header,
97        };
98        Ok(())
99    }
100}
101
102#[derive(Debug, Clone, Copy)]
103pub struct RowsEvent<'a> {
104    pub table_id: u64,
105    pub flags: u16,
106    pub kind: RowsKind,
107    /// Extra data, bitmaps and values are delayed until after table selection.
108    pub encoded_images: &'a [u8],
109    pub(crate) post_header: usize,
110    pub(crate) v2: bool,
111}
112impl RowsEvent<'_> {
113    pub fn with_layout(kind: RowsKind, post_header: usize, v2: bool) -> Self {
114        Self {
115            table_id: 0,
116            flags: 0,
117            kind,
118            encoded_images: &[],
119            post_header,
120            v2,
121        }
122    }
123    pub fn images(&self) -> Result<RowImages<'_>> {
124        let mut input = Cursor::new(self.encoded_images);
125        let extra_data = if self.v2 {
126            let length = input.le(2)? as usize;
127            input.take(
128                length
129                    .checked_sub(2)
130                    .ok_or_else(|| invalid("extra-data length < 2"))?,
131            )?
132        } else {
133            &[]
134        };
135        let column_count = input.lenenc()?;
136        if column_count == 0 || column_count > 4096 {
137            return Err(invalid("ROWS column count outside 1..4096"));
138        }
139        let first = input.take(column_count.div_ceil(8))?;
140        let second = if self.kind == RowsKind::Update {
141            input.take(column_count.div_ceil(8))?
142        } else {
143            first
144        };
145        Ok(RowImages {
146            extra_data,
147            column_count,
148            before_columns: first,
149            after_columns: second,
150            rows: input.remaining(),
151        })
152    }
153}
154impl<'a> Event<'a> for RowsEvent<'a> {
155    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
156        writeln!(writer, "Table ID: {}", self.table_id)?;
157        writeln!(writer, "Flags: {}", self.flags)?;
158        writeln!(writer, "Kind: {:?}", self.kind)?;
159        writeln!(writer, "Encoded images: {:02x?}", self.encoded_images)?;
160        writeln!(writer)?;
161        Ok(())
162    }
163
164    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
165        let width = self
166            .post_header
167            .checked_sub(if self.v2 { 4 } else { 2 })
168            .ok_or_else(|| invalid("short ROWS post-header"))?;
169        if !matches!(width, 4 | 6) {
170            return Err(invalid("unsupported ROWS table ID width"));
171        }
172        let mut input = Cursor::new(data);
173        let table_id = input.le(width)?;
174        let flags = input.le(2)? as u16;
175        self.table_id = table_id;
176        self.flags = flags;
177        self.encoded_images = input.remaining();
178        Ok(())
179    }
180}
181#[derive(Debug, Clone, Copy)]
182pub struct RowImages<'a> {
183    pub extra_data: &'a [u8],
184    pub column_count: usize,
185    pub before_columns: &'a [u8],
186    pub after_columns: &'a [u8],
187    pub rows: &'a [u8],
188}