Skip to main content

mysql_replication/events/rows/
typed.rs

1//! Typed, borrowed image views over the common ROWS wire layout.
2use super::{
3    ColumnDefinition, RowFields, RowImage, RowValue, Rows, RowsDecoder, RowsEvent, RowsKind,
4};
5use crate::{
6    Error, Result,
7    config::RowImageMode,
8    error::invalid,
9    events::{BinlogMode, TableMapEvent},
10};
11use std::{fmt::Debug, iter::FusedIterator, marker::PhantomData};
12
13mod sealed {
14    pub trait Sealed {}
15}
16
17/// A supported image policy with its own borrowed image representation.
18///
19/// This trait is sealed so that a typed FULL event cannot bypass completeness
20/// validation. Modes describe accepted shapes, not a producer setting inferred
21/// from the bytes. MINIMAL may contain all columns and does not require a key.
22pub trait ImageMode: sealed::Sealed + BinlogMode + Send + Sync + 'static {
23    type Image<'a>: TryFrom<RowImage<'a>, Error = Error> + AsRef<RowImage<'a>> + Debug + Clone;
24    #[doc(hidden)]
25    const REQUIRE_COMPLETE: bool;
26    const ROW_IMAGE: RowImageMode;
27    #[doc(hidden)]
28    fn validate_rows(rows: &Rows<'_>) -> Result<()>;
29}
30
31/// Sparse images retain only the columns actually present in the binlog.
32#[derive(Debug, Clone, Copy)]
33pub struct Minimal;
34impl sealed::Sealed for Minimal {}
35impl ImageMode for Minimal {
36    type Image<'a> = SparseImage<'a>;
37    const REQUIRE_COMPLETE: bool = false;
38    const ROW_IMAGE: RowImageMode = RowImageMode::Minimal;
39    fn validate_rows(_: &Rows<'_>) -> Result<()> {
40        Ok(())
41    }
42}
43
44/// Every column must be present in every existing image.
45#[derive(Debug, Clone, Copy)]
46pub struct Full;
47impl sealed::Sealed for Full {}
48impl ImageMode for Full {
49    type Image<'a> = CompleteImage<'a>;
50    const REQUIRE_COMPLETE: bool = true;
51    const ROW_IMAGE: RowImageMode = RowImageMode::Full;
52    fn validate_rows(rows: &Rows<'_>) -> Result<()> {
53        rows.require_complete()
54    }
55}
56
57/// A borrowed sparse image. A missing field is distinct from SQL NULL.
58///
59/// An image cannot outlive its input bytes, even after its decoder is dropped.
60///
61/// ```compile_fail
62/// use mysql_replication::events::SparseImage;
63/// fn retain_forever<'a>(image: SparseImage<'a>) -> SparseImage<'static> {
64///     image
65/// }
66/// ```
67#[derive(Debug, Clone)]
68pub struct SparseImage<'a> {
69    image: RowImage<'a>,
70}
71impl<'a> SparseImage<'a> {
72    pub fn column_count(&self) -> usize {
73        self.image.column_count()
74    }
75    pub fn column_indices(&self) -> &[u16] {
76        self.image.column_indices()
77    }
78    pub fn fields(&self) -> RowFields<'_, 'a> {
79        self.image.fields()
80    }
81    /// Reads through present fields up to this absolute index, without allocating.
82    /// Returns `None` for an absent column, including an out-of-range index.
83    pub fn field(&self, column_index: usize) -> Result<Option<RowValue<'a>>> {
84        field(&self.image, column_index)
85    }
86}
87impl<'a> TryFrom<RowImage<'a>> for SparseImage<'a> {
88    type Error = Error;
89    fn try_from(image: RowImage<'a>) -> Result<Self> {
90        Ok(Self { image })
91    }
92}
93impl<'a> AsRef<RowImage<'a>> for SparseImage<'a> {
94    fn as_ref(&self) -> &RowImage<'a> {
95        &self.image
96    }
97}
98
99/// A borrowed image whose columns have all been validated as present.
100///
101/// Construction is checked; converting a sparse prefix cannot claim completeness.
102/// This does not allocate a full row or interpret SQL signedness/character sets.
103#[derive(Debug, Clone)]
104pub struct CompleteImage<'a> {
105    image: RowImage<'a>,
106}
107impl<'a> CompleteImage<'a> {
108    pub fn column_count(&self) -> usize {
109        self.image.column_count()
110    }
111    pub fn fields(&self) -> RowFields<'_, 'a> {
112        self.image.fields()
113    }
114    /// Reads through fields up to this absolute index, without allocating.
115    /// Every in-range column exists; SQL NULL is `RowValue::Null`.
116    pub fn field(&self, column_index: usize) -> Result<RowValue<'a>> {
117        if column_index >= self.column_count() {
118            return Err(invalid("column index outside complete row image"));
119        }
120        field(&self.image, column_index)?.ok_or_else(|| invalid("incomplete FULL row image"))
121    }
122}
123impl<'a> TryFrom<RowImage<'a>> for CompleteImage<'a> {
124    type Error = Error;
125    fn try_from(image: RowImage<'a>) -> Result<Self> {
126        if image.column_indices().len() != image.column_count() {
127            return Err(Error::Unsupported(
128                "FULL row images must contain every table column".into(),
129            ));
130        }
131        Ok(Self { image })
132    }
133}
134impl<'a> AsRef<RowImage<'a>> for CompleteImage<'a> {
135    fn as_ref(&self) -> &RowImage<'a> {
136        &self.image
137    }
138}
139
140fn field<'a>(image: &RowImage<'a>, index: usize) -> Result<Option<RowValue<'a>>> {
141    for field in image.fields() {
142        let field = field?;
143        let column_index = usize::from(field.column_index);
144        if column_index == index {
145            return Ok(Some(field.value));
146        }
147        if column_index > index {
148            break;
149        }
150    }
151    Ok(None)
152}
153
154/// One operation with mode-specific image types. Missing images remain `None`.
155///
156/// The modes have distinct image types even when their bitmaps happen to match.
157///
158/// ```compile_fail
159/// use mysql_replication::events::{Full, Minimal, TypedRow};
160/// fn sparse(row: TypedRow<'_, Full>) -> TypedRow<'_, Minimal> {
161///     row
162/// }
163/// ```
164#[derive(Debug, Clone)]
165pub struct TypedRow<'a, M: ImageMode> {
166    /// Before image for UPDATE/DELETE; `None` for INSERT. The image is sparse
167    /// under `Minimal` and complete under `Full`; SQL NULL is a field value.
168    pub before: Option<M::Image<'a>>,
169    /// After image for INSERT/UPDATE; `None` for DELETE, with the same mode's
170    /// image type as `before`.
171    pub after: Option<M::Image<'a>>,
172}
173
174/// A ROWS event with checked image shape and an owned TABLE_MAP execution plan.
175///
176/// Private fields prevent bypassing the mode check. Values still borrow the
177/// input and are validated while iterating; a malformed row never yields a
178/// partially decoded operation. The source decoder can be dropped immediately.
179pub struct TypedRowsEvent<'a, M: ImageMode> {
180    event: RowsEvent<'a>,
181    rows: Rows<'a>,
182    column_count: usize,
183    mode: PhantomData<M>,
184}
185impl<'a, M: ImageMode> TypedRowsEvent<'a, M> {
186    pub(super) fn new(event: RowsEvent<'a>, decoder: &RowsDecoder) -> Result<Self> {
187        let rows = decoder.rows(&event)?;
188        M::validate_rows(&rows)?;
189        Ok(Self {
190            event,
191            rows,
192            column_count: decoder.columns().len(),
193            mode: PhantomData,
194        })
195    }
196    pub fn table_id(&self) -> u64 {
197        self.event.table_id
198    }
199    pub fn flags(&self) -> u16 {
200        self.event.flags
201    }
202    pub fn kind(&self) -> RowsKind {
203        self.event.kind
204    }
205    pub fn column_count(&self) -> usize {
206        self.column_count
207    }
208    pub fn rows(self) -> TypedRows<'a, M> {
209        TypedRows {
210            rows: self.rows,
211            done: false,
212            mode: PhantomData,
213        }
214    }
215}
216
217/// A mode-specific streaming iterator. It yields one error and then stops.
218pub struct TypedRows<'a, M: ImageMode> {
219    rows: Rows<'a>,
220    done: bool,
221    mode: PhantomData<M>,
222}
223impl<'a, M: ImageMode> Iterator for TypedRows<'a, M> {
224    type Item = Result<TypedRow<'a, M>>;
225    fn next(&mut self) -> Option<Self::Item> {
226        if self.done {
227            return None;
228        }
229        let result = self.rows.next()?.and_then(|row| {
230            Ok(TypedRow {
231                before: row.before.map(M::Image::try_from).transpose()?,
232                after: row.after.map(M::Image::try_from).transpose()?,
233            })
234        });
235        self.done = result.is_err();
236        Some(result)
237    }
238}
239impl<M: ImageMode> FusedIterator for TypedRows<'_, M> {}
240
241/// A reusable generic decoder, bound to a TABLE_MAP and an image policy.
242#[derive(Debug)]
243pub struct TypedRowsDecoder<M: ImageMode> {
244    decoder: RowsDecoder,
245    mode: PhantomData<M>,
246}
247impl<M: ImageMode> TypedRowsDecoder<M> {
248    pub fn new(table: &TableMapEvent<'_>) -> Result<Self> {
249        RowsDecoder::new(table).map(Self::from)
250    }
251    pub fn table_id(&self) -> u64 {
252        self.decoder.table_id()
253    }
254    pub fn columns(&self) -> &[ColumnDefinition] {
255        self.decoder.columns()
256    }
257    pub fn event<'a>(&self, event: &RowsEvent<'a>) -> Result<TypedRowsEvent<'a, M>> {
258        event.with_mode::<M>(&self.decoder)
259    }
260    pub fn rows<'a>(&self, event: &RowsEvent<'a>) -> Result<TypedRows<'a, M>> {
261        self.event(event).map(TypedRowsEvent::rows)
262    }
263}
264impl<M: ImageMode> From<RowsDecoder> for TypedRowsDecoder<M> {
265    fn from(decoder: RowsDecoder) -> Self {
266        Self {
267            decoder,
268            mode: PhantomData,
269        }
270    }
271}