mysql_common/binlog/events/
rows_query_event.rs

1// Copyright (c) 2021 Anatoly Ikorsky
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9use std::{borrow::Cow, cmp::min, io};
10
11use saturating::Saturating as S;
12
13use crate::{
14    binlog::{
15        consts::{BinlogVersion, EventType},
16        BinlogCtx, BinlogEvent, BinlogStruct,
17    },
18    io::ParseBuf,
19    misc::raw::{bytes::EofBytes, RawBytes, Skip},
20    proto::{MyDeserialize, MySerialize},
21};
22
23use super::BinlogEventHeader;
24
25/// Query that caused the following `ROWS_EVENT`.
26///
27/// It is used to write the original query in the binlog file in case of row-based replication
28/// when the session flag `binlog_rows_query_log_events` is set.
29#[derive(Debug, Clone, Eq, PartialEq, Hash)]
30pub struct RowsQueryEvent<'a> {
31    /// Length is ignored.
32    length: Skip<1>,
33    query: RawBytes<'a, EofBytes>,
34}
35
36impl<'a> RowsQueryEvent<'a> {
37    /// Creates a new `RowsQueryEvent`.
38    pub fn new(query: impl Into<Cow<'a, [u8]>>) -> Self {
39        Self {
40            length: Default::default(),
41            query: RawBytes::new(query),
42        }
43    }
44
45    /// Returns the raw query.
46    pub fn query_raw(&'a self) -> &'a [u8] {
47        self.query.as_bytes()
48    }
49
50    /// Returns query as a string (lossy converted).
51    pub fn query(&'a self) -> Cow<'a, str> {
52        self.query.as_str()
53    }
54
55    pub fn into_owned(self) -> RowsQueryEvent<'static> {
56        RowsQueryEvent {
57            length: self.length,
58            query: self.query.into_owned(),
59        }
60    }
61}
62
63impl<'de> MyDeserialize<'de> for RowsQueryEvent<'de> {
64    const SIZE: Option<usize> = None;
65    type Ctx = BinlogCtx<'de>;
66
67    fn deserialize(_ctx: Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
68        Ok(Self {
69            length: buf.parse(())?,
70            query: buf.parse(())?,
71        })
72    }
73}
74
75impl MySerialize for RowsQueryEvent<'_> {
76    fn serialize(&self, buf: &mut Vec<u8>) {
77        self.length.serialize(&mut *buf);
78        self.query.serialize(&mut *buf);
79    }
80}
81
82impl<'a> BinlogEvent<'a> for RowsQueryEvent<'a> {
83    const EVENT_TYPE: EventType = EventType::ROWS_QUERY_EVENT;
84}
85
86impl<'a> BinlogStruct<'a> for RowsQueryEvent<'a> {
87    fn len(&self, _version: BinlogVersion) -> usize {
88        let mut len = S(0);
89
90        len += S(1);
91        len += S(self.query.0.len());
92
93        min(len.0, u32::MAX as usize - BinlogEventHeader::LEN)
94    }
95}