mysqlbinlog_network/mysql_binlog/
value.rs

1use base64;
2
3use std::borrow::Cow;
4
5use serde::{Serialize, Serializer};
6use serde_derive::Serialize;
7use serde_json;
8
9#[derive(Debug)]
10/// Wrapper for the SQL BLOB (Binary Large OBject) type
11///
12/// Serializes as Base64
13pub struct Blob(Vec<u8>);
14
15impl From<Vec<u8>> for Blob {
16    fn from(v: Vec<u8>) -> Self {
17        Blob(v)
18    }
19}
20
21impl Serialize for Blob {
22    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
23    where
24        S: Serializer,
25    {
26        let serialized = base64::encode(&self.0);
27        serializer.serialize_str(&serialized)
28    }
29}
30
31#[derive(Debug, Serialize)]
32/// Normalized representation of types which are present in MySQL
33pub enum MySQLValue {
34    SignedInteger(i64),
35    Float(f32),
36    Double(f64),
37    String(String),
38    Enum(i16),
39    Blob(Blob),
40    Year(u32),
41    Date {
42        year: u32,
43        month: u32,
44        day: u32,
45    },
46    Time {
47        hours: u32,
48        minutes: u32,
49        seconds: u32,
50        subseconds: u32,
51    },
52    DateTime {
53        year: u32,
54        month: u32,
55        day: u32,
56        hour: u32,
57        minute: u32,
58        second: u32,
59        subsecond: u32,
60    },
61    Json(serde_json::Value),
62    Decimal(bigdecimal::BigDecimal),
63    Timestamp {
64        unix_time: i32,
65        subsecond: u32,
66    },
67    Null,
68}
69
70impl MySQLValue {
71    /// Turn this type into a serde_json::Value
72    ///
73    /// Tries to avoid round-tripping through Serialize if it can
74    pub(crate) fn as_value(&self) -> Result<Cow<serde_json::Value>, serde_json::error::Error> {
75        match *self {
76            MySQLValue::Json(ref j) => Ok(Cow::Borrowed(j)),
77            MySQLValue::Null => Ok(Cow::Owned(serde_json::Value::Null)),
78            ref j => Ok(Cow::Owned(serde_json::to_value(j)?)),
79        }
80    }
81}