1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use std::{borrow::Cow, io};

use crate::{
    constants::SessionStateType,
    io::ParseBuf,
    misc::raw::{bytes::EofBytes, int::LenEnc, RawBytes},
    proto::{MyDeserialize, MySerialize},
};

// Copyright (c) 2017 Anatoly Ikorsky
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

/// Represents a parsed change in a session state (part of MySql's Ok packet).
///
/// See [MySql docs][1].
///
/// [1]: https://dev.mysql.com/doc/c-api/5.7/en/mysql-session-track-get-first.html
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum SessionStateChange<'a> {
    IsTracked(bool),
    Schema(Schema<'a>),
    SystemVariables(Vec<SystemVariable<'a>>),
    Gtids(Gtids<'a>),
    TransactionCharacteristics(TransactionCharacteristics<'a>),
    TransactionState(TransactionState<'a>),
    Unsupported(Unsupported<'a>),
}

impl<'a> SessionStateChange<'a> {
    pub fn into_owned(self) -> SessionStateChange<'static> {
        match self {
            SessionStateChange::SystemVariables(x) => SessionStateChange::SystemVariables(
                x.into_iter().map(SystemVariable::into_owned).collect(),
            ),
            SessionStateChange::Schema(schema) => SessionStateChange::Schema(schema.into_owned()),
            SessionStateChange::IsTracked(x) => SessionStateChange::IsTracked(x),
            SessionStateChange::Gtids(x) => SessionStateChange::Gtids(x.into_owned()),
            SessionStateChange::TransactionCharacteristics(x) => {
                SessionStateChange::TransactionCharacteristics(x.into_owned())
            }
            SessionStateChange::TransactionState(x) => {
                SessionStateChange::TransactionState(x.into_owned())
            }
            SessionStateChange::Unsupported(x) => SessionStateChange::Unsupported(x.into_owned()),
        }
    }
}

impl<'de> MyDeserialize<'de> for SessionStateChange<'de> {
    const SIZE: Option<usize> = None;
    type Ctx = SessionStateType;

    fn deserialize(ty: SessionStateType, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
        match ty {
            SessionStateType::SESSION_TRACK_SYSTEM_VARIABLES => {
                let mut vars = Vec::new();
                while !buf.is_empty() {
                    vars.push(buf.parse_unchecked(())?);
                }
                Ok(SessionStateChange::SystemVariables(vars))
            }
            SessionStateType::SESSION_TRACK_SCHEMA => {
                buf.parse_unchecked(()).map(SessionStateChange::Schema)
            }
            SessionStateType::SESSION_TRACK_STATE_CHANGE => {
                let is_tracked: RawBytes<'_, LenEnc> = buf.parse_unchecked(())?;
                Ok(SessionStateChange::IsTracked(is_tracked.as_bytes() == b"1"))
            }
            // Layout isn't specified in the documentation
            SessionStateType::SESSION_TRACK_GTIDS => {
                Ok(SessionStateChange::Gtids(buf.parse_unchecked(())?))
            }
            SessionStateType::SESSION_TRACK_TRANSACTION_CHARACTERISTICS => Ok(
                SessionStateChange::TransactionCharacteristics(buf.parse_unchecked(())?),
            ),
            SessionStateType::SESSION_TRACK_TRANSACTION_STATE => buf
                .parse_unchecked(())
                .map(SessionStateChange::TransactionState),
        }
    }
}

impl MySerialize for SessionStateChange<'_> {
    fn serialize(&self, buf: &mut Vec<u8>) {
        match self {
            SessionStateChange::SystemVariables(vars) => {
                for var in vars {
                    var.serialize(&mut *buf);
                }
            }
            SessionStateChange::Schema(schema) => schema.serialize(buf),
            SessionStateChange::IsTracked(is_tracked) => {
                if *is_tracked {
                    b"\x011".serialize(buf);
                } else {
                    b"\x010".serialize(buf);
                }
            }
            SessionStateChange::Gtids(x) => x.serialize(buf),
            SessionStateChange::TransactionCharacteristics(x) => x.serialize(buf),
            SessionStateChange::TransactionState(x) => x.serialize(buf),
            SessionStateChange::Unsupported(x) => x.serialize(buf),
        }
    }
}

/// This tracker type indicates that GTIDs are available and contains the GTID string.
///
/// The GTID string is in the standard format for specifying a set of GTID values.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Gtids<'a>(RawBytes<'a, EofBytes>);

impl<'a> Gtids<'a> {
    pub fn new(gtid_set: impl Into<Cow<'a, [u8]>>) -> Self {
        Self(RawBytes::new(gtid_set))
    }

    /// Returns a raw GTID string.
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Returns a GTID string (lossy converted).
    pub fn as_str(&self) -> Cow<'_, str> {
        self.0.as_str()
    }

    /// Returns a `'static` version of self.
    pub fn into_owned(self) -> Gtids<'static> {
        Gtids(self.0.into_owned())
    }
}

impl<'de> MyDeserialize<'de> for Gtids<'de> {
    const SIZE: Option<usize> = None;
    type Ctx = ();

    fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
        buf.parse_unchecked(()).map(Self)
    }
}

impl MySerialize for Gtids<'_> {
    fn serialize(&self, buf: &mut Vec<u8>) {
        self.0.serialize(buf);
    }
}

/// This tracker type indicates that the default schema has been set.
///
/// The value contains the new default schema name.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Schema<'a>(RawBytes<'a, LenEnc>);

impl<'a> Schema<'a> {
    pub fn new(schema_name: impl Into<Cow<'a, [u8]>>) -> Self {
        Self(RawBytes::new(schema_name))
    }

    /// Returns a raw schema name.
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Returns schema name (lossy converted).
    pub fn as_str(&self) -> Cow<'_, str> {
        self.0.as_str()
    }

    /// Returns a `'static` version of `self`.
    pub fn into_owned(self) -> Schema<'static> {
        Schema(self.0.into_owned())
    }
}

impl<'de> MyDeserialize<'de> for Schema<'de> {
    const SIZE: Option<usize> = None;
    type Ctx = ();

    fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
        buf.parse_unchecked(()).map(Self)
    }
}

impl MySerialize for Schema<'_> {
    fn serialize(&self, buf: &mut Vec<u8>) {
        self.0.serialize(buf);
    }
}

/// This tracker type indicates that one or more tracked session
/// system variables have been assigned a value.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SystemVariable<'a> {
    name: RawBytes<'a, LenEnc>,
    value: RawBytes<'a, LenEnc>,
}

impl<'a> SystemVariable<'a> {
    pub fn new(name: impl Into<Cow<'a, [u8]>>, value: impl Into<Cow<'a, [u8]>>) -> Self {
        Self {
            name: RawBytes::new(name),
            value: RawBytes::new(value),
        }
    }

    /// Returns a raw name.
    pub fn name_bytes(&self) -> &[u8] {
        self.name.as_bytes()
    }

    /// Returns a name (lossy converted).
    pub fn name_str(&self) -> Cow<'_, str> {
        self.name.as_str()
    }

    /// Returns a raw value.
    pub fn value_bytes(&self) -> &[u8] {
        self.value.as_bytes()
    }

    /// Returns a value (lossy converted).
    pub fn value_str(&self) -> Cow<'_, str> {
        self.value.as_str()
    }

    /// Returns a `'static` version of `self`.
    pub fn into_owned(self) -> SystemVariable<'static> {
        SystemVariable {
            name: self.name.into_owned(),
            value: self.value.into_owned(),
        }
    }
}

impl<'de> MyDeserialize<'de> for SystemVariable<'de> {
    const SIZE: Option<usize> = None;
    type Ctx = ();

    fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
        Ok(Self {
            name: buf.parse_unchecked(())?,
            value: buf.parse_unchecked(())?,
        })
    }
}

impl MySerialize for SystemVariable<'_> {
    fn serialize(&self, buf: &mut Vec<u8>) {
        self.name.serialize(&mut *buf);
        self.value.serialize(buf);
    }
}

/// This tracker type indicates that transaction characteristics are available.
///
/// The characteristics tracker data string may be empty,
/// or it may contain one or more SQL statements, each terminated by a semicolon.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TransactionCharacteristics<'a>(RawBytes<'a, LenEnc>);

impl<'a> TransactionCharacteristics<'a> {
    pub fn new(value: impl Into<Cow<'a, [u8]>>) -> Self {
        Self(RawBytes::new(value))
    }

    /// Returns a raw value.
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Returns a value (lossy converted).
    pub fn as_str(&self) -> Cow<'_, str> {
        self.0.as_str()
    }

    /// Returns a `'static` version of `self`.
    pub fn into_owned(self) -> TransactionCharacteristics<'static> {
        TransactionCharacteristics(self.0.into_owned())
    }
}

impl<'de> MyDeserialize<'de> for TransactionCharacteristics<'de> {
    const SIZE: Option<usize> = None;
    type Ctx = ();

    fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
        buf.parse_unchecked(()).map(Self)
    }
}

impl MySerialize for TransactionCharacteristics<'_> {
    fn serialize(&self, buf: &mut Vec<u8>) {
        self.0.serialize(buf);
    }
}

/// This tracker type indicates that transaction state information is available.
///
/// Value is a string containing ASCII characters, each of which indicates some aspect
/// of the transaction state.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TransactionState<'a>(RawBytes<'a, LenEnc>);

impl<'a> TransactionState<'a> {
    pub fn new(value: impl Into<Cow<'a, [u8]>>) -> Self {
        Self(RawBytes::new(value))
    }

    /// Returns a raw value.
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Returns a value (lossy converted).
    pub fn as_str(&self) -> Cow<'_, str> {
        self.0.as_str()
    }

    /// Returns a `'static` version of `self`.
    pub fn into_owned(self) -> TransactionState<'static> {
        TransactionState(self.0.into_owned())
    }
}

impl<'de> MyDeserialize<'de> for TransactionState<'de> {
    const SIZE: Option<usize> = None;
    type Ctx = ();

    fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
        buf.parse_unchecked(()).map(Self)
    }
}

impl MySerialize for TransactionState<'_> {
    fn serialize(&self, buf: &mut Vec<u8>) {
        self.0.serialize(buf);
    }
}

/// This tracker type is unknown/unsupported.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Unsupported<'a>(RawBytes<'a, LenEnc>);

impl<'a> Unsupported<'a> {
    pub fn new(value: impl Into<Cow<'a, [u8]>>) -> Self {
        Self(RawBytes::new(value))
    }

    /// Returns a value as a slice of bytes.
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Returns a value as a string (lossy converted).
    pub fn as_str(&self) -> Cow<'_, str> {
        self.0.as_str()
    }

    /// Returns a `'static` version of `self`.
    pub fn into_owned(self) -> Unsupported<'static> {
        Unsupported(self.0.into_owned())
    }
}

impl<'de> MyDeserialize<'de> for Unsupported<'de> {
    const SIZE: Option<usize> = None;
    type Ctx = ();

    fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
        buf.parse_unchecked(()).map(Self)
    }
}

impl MySerialize for Unsupported<'_> {
    fn serialize(&self, buf: &mut Vec<u8>) {
        self.0.serialize(buf);
    }
}