sqlparser_mysql/base/
compression_type.rs

1use nom::branch::alt;
2use nom::bytes::complete::{tag, tag_no_case};
3use nom::character::complete::{multispace0, multispace1};
4use nom::combinator::{map, opt};
5use nom::sequence::{delimited, tuple};
6use nom::IResult;
7use std::fmt::{Display, Formatter};
8
9use base::ParseSQLError;
10
11/// parse `COMPRESSION [=] {'ZLIB' | 'LZ4' | 'NONE'}`
12#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
13pub enum CompressionType {
14    ZLIB,
15    LZ4,
16    NONE,
17}
18
19impl Display for CompressionType {
20    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
21        match *self {
22            CompressionType::ZLIB => write!(f, "COMPRESSION 'ZLIB'"),
23            CompressionType::LZ4 => write!(f, "COMPRESSION 'LZ4'"),
24            CompressionType::NONE => write!(f, "COMPRESSION 'NONE'"),
25        }
26    }
27}
28
29impl CompressionType {
30    pub fn parse(i: &str) -> IResult<&str, CompressionType, ParseSQLError<&str>> {
31        alt((
32            map(
33                tuple((
34                    tag_no_case("COMPRESSION"),
35                    multispace1,
36                    Self::parse_compression,
37                )),
38                |(_, _, compression_type)| compression_type,
39            ),
40            map(
41                tuple((
42                    tag_no_case("COMPRESSION"),
43                    multispace0,
44                    tag("="),
45                    multispace0,
46                    Self::parse_compression,
47                )),
48                |(_, _, _, _, compression_type)| compression_type,
49            ),
50        ))(i)
51    }
52
53    fn parse_compression(i: &str) -> IResult<&str, CompressionType, ParseSQLError<&str>> {
54        alt((
55            map(
56                alt((tag_no_case("'ZLIB'"), tag_no_case("\"ZLIB\""))),
57                |_| CompressionType::ZLIB,
58            ),
59            map(alt((tag_no_case("'LZ4'"), tag_no_case("\"LZ4\""))), |_| {
60                CompressionType::LZ4
61            }),
62            map(
63                alt((tag_no_case("'NONE'"), tag_no_case("\"NONE\""))),
64                |_| CompressionType::NONE,
65            ),
66        ))(i)
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use base::CompressionType;
73
74    #[test]
75    fn parse_compression_type() {
76        let str1 = "COMPRESSION 'ZLIB'";
77        let res1 = CompressionType::parse(str1);
78        assert!(res1.is_ok());
79        assert_eq!(res1.unwrap().1, CompressionType::ZLIB);
80    }
81}