Skip to main content

mysql_replication/events/rows/
metadata.rs

1//! Owned TABLE_MAP definitions shared by events and borrowed row images.
2use super::ColumnDefinition;
3use crate::{Result, error::invalid, events::TableMapEvent, wire::Cursor};
4use mysql_common::binlog::consts::OptionalMetadataFieldType as Tag;
5use std::sync::Arc;
6
7/// Protocol metadata only; absent optional attributes are never guessed.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct ColumnInfo {
10    pub index: u16,
11    pub name: Option<Box<str>>,
12    pub definition: ColumnDefinition,
13    pub unsigned: Option<bool>,
14    pub collation_id: Option<u32>,
15    pub primary_key: Option<bool>,
16    /// Character prefix length; zero means the entire key column.
17    pub primary_key_prefix: Option<usize>,
18}
19/// A historical definition copied once from TABLE_MAP, with no server queries.
20#[derive(Debug)]
21pub struct TableDefinition {
22    pub schema: Box<[u8]>,
23    pub table: Box<[u8]>,
24    pub columns: Arc<[ColumnInfo]>,
25    /// Original optional TLVs, including attributes not interpreted by this API.
26    pub optional_metadata: Box<[u8]>,
27}
28impl TableDefinition {
29    pub(super) fn new(
30        table: &TableMapEvent<'_>,
31        definitions: Vec<ColumnDefinition>,
32        optional: &[u8],
33    ) -> Result<Self> {
34        let mut columns: Vec<_> = definitions
35            .into_iter()
36            .enumerate()
37            .map(|(index, definition)| ColumnInfo {
38                index: index as u16,
39                name: None,
40                definition,
41                unsigned: None,
42                collation_id: None,
43                primary_key: None,
44                primary_key_prefix: None,
45            })
46            .collect();
47        let mut input = Cursor::new(optional);
48        let mut seen = [false; 256];
49        while !input.remaining().is_empty() {
50            let tag = input.byte()?;
51            if std::mem::replace(&mut seen[usize::from(tag)], true) {
52                return Err(invalid("duplicate TABLE_MAP optional metadata"));
53            }
54            let length = input.lenenc()?;
55            let data = input.take(length)?;
56            let mut value = Cursor::new(data);
57            match tag {
58                x if x == Tag::SIGNEDNESS as u8 => {
59                    let numeric: Vec<_> = columns
60                        .iter_mut()
61                        .filter(|c| c.definition.column_type().is_numeric_type())
62                        .collect();
63                    if data.len() != numeric.len().div_ceil(8) {
64                        return Err(invalid("TABLE_MAP signedness bitmap length"));
65                    }
66                    for (i, column) in numeric.into_iter().enumerate() {
67                        column.unsigned = Some(data[i / 8] & (0x80 >> (i % 8)) != 0);
68                    }
69                }
70                x if x == Tag::COLUMN_NAME as u8 => {
71                    for column in &mut columns {
72                        let length = value.lenenc()?;
73                        let name = std::str::from_utf8(value.take(length)?)?;
74                        if name.is_empty() {
75                            return Err(invalid("empty TABLE_MAP column name"));
76                        }
77                        column.name = Some(name.into());
78                    }
79                    value.finish()?;
80                }
81                x if x == Tag::DEFAULT_CHARSET as u8 || x == Tag::COLUMN_CHARSET as u8 => {
82                    charsets(
83                        &mut columns,
84                        &mut value,
85                        x == Tag::DEFAULT_CHARSET as u8,
86                        false,
87                    )?;
88                }
89                x if x == Tag::ENUM_AND_SET_DEFAULT_CHARSET as u8
90                    || x == Tag::ENUM_AND_SET_COLUMN_CHARSET as u8 =>
91                {
92                    charsets(
93                        &mut columns,
94                        &mut value,
95                        x == Tag::ENUM_AND_SET_DEFAULT_CHARSET as u8,
96                        true,
97                    )?;
98                }
99                x if x == Tag::SIMPLE_PRIMARY_KEY as u8
100                    || x == Tag::PRIMARY_KEY_WITH_PREFIX as u8 =>
101                {
102                    if columns.iter().any(|c| c.primary_key.is_some()) {
103                        return Err(invalid("conflicting TABLE_MAP primary-key metadata"));
104                    }
105                    for column in &mut columns {
106                        column.primary_key = Some(false);
107                    }
108                    while !value.remaining().is_empty() {
109                        let index = value.lenenc()?;
110                        let column = columns.get_mut(index).ok_or_else(|| {
111                            invalid("TABLE_MAP primary-key index outside columns")
112                        })?;
113                        if column.primary_key == Some(true) {
114                            return Err(invalid("duplicate TABLE_MAP primary-key index"));
115                        }
116                        column.primary_key = Some(true);
117                        column.primary_key_prefix =
118                            Some(if x == Tag::PRIMARY_KEY_WITH_PREFIX as u8 {
119                                value.lenenc()?
120                            } else {
121                                0
122                            });
123                    }
124                }
125                _ => {}
126            }
127        }
128        Ok(Self {
129            schema: table.schema.into(),
130            table: table.table.into(),
131            columns: columns.into(),
132            optional_metadata: optional.into(),
133        })
134    }
135}
136
137fn charsets(
138    columns: &mut [ColumnInfo],
139    input: &mut Cursor<'_>,
140    default: bool,
141    enum_set: bool,
142) -> Result<()> {
143    let selected: Vec<_> = columns
144        .iter_mut()
145        .filter(|c| {
146            if enum_set {
147                c.definition.column_type().is_enum_or_set_type()
148            } else {
149                c.definition.column_type().is_character_type()
150            }
151        })
152        .collect();
153    if selected.iter().any(|c| c.collation_id.is_some()) {
154        return Err(invalid("conflicting TABLE_MAP charset metadata"));
155    }
156    let read_collation = |input: &mut Cursor<'_>| -> Result<u32> {
157        u32::try_from(input.lenenc()?).map_err(|_| invalid("TABLE_MAP collation overflows u32"))
158    };
159    if default {
160        let collation = read_collation(input)?;
161        let mut selected = selected;
162        let mut seen = vec![false; selected.len()];
163        for column in &mut selected {
164            column.collation_id = Some(collation);
165        }
166        while !input.remaining().is_empty() {
167            let index = input.lenenc()?;
168            let column = selected
169                .get_mut(index)
170                .ok_or_else(|| invalid("TABLE_MAP charset index outside character columns"))?;
171            if std::mem::replace(&mut seen[index], true) {
172                return Err(invalid("duplicate TABLE_MAP charset index"));
173            }
174            column.collation_id = Some(read_collation(input)?);
175        }
176    } else {
177        for column in selected {
178            column.collation_id = Some(read_collation(input)?);
179        }
180        if !input.remaining().is_empty() {
181            return Err(invalid("TABLE_MAP charset count differs from columns"));
182        }
183    }
184    Ok(())
185}