sqlparser_mysql/base/
index_type.rs

1use core::fmt;
2use std::fmt::Formatter;
3
4use nom::branch::alt;
5use nom::bytes::complete::tag_no_case;
6use nom::character::complete::{multispace0, multispace1};
7use nom::combinator::{map, opt};
8use nom::sequence::{delimited, tuple};
9use nom::IResult;
10
11use base::ParseSQLError;
12
13/// parse `USING {BTREE | HASH}`
14#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
15pub enum IndexType {
16    Btree,
17    Hash,
18}
19
20impl IndexType {
21    pub fn parse(i: &str) -> IResult<&str, IndexType, ParseSQLError<&str>> {
22        map(
23            tuple((
24                tag_no_case("USING"),
25                multispace1,
26                alt((
27                    map(tag_no_case("BTREE"), |_| IndexType::Btree),
28                    map(tag_no_case("HASH"), |_| IndexType::Hash),
29                )),
30            )),
31            |x| x.2,
32        )(i)
33    }
34
35    /// `[index_type]`
36    /// USING {BTREE | HASH}
37    pub fn opt_index_type(i: &str) -> IResult<&str, Option<IndexType>, ParseSQLError<&str>> {
38        opt(map(
39            delimited(multispace1, IndexType::parse, multispace0),
40            |x| x,
41        ))(i)
42    }
43}
44
45impl fmt::Display for IndexType {
46    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47        match self {
48            IndexType::Btree => write!(f, "USING BTREE")?,
49            IndexType::Hash => write!(f, "USING HASH")?,
50        };
51        Ok(())
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use base::index_type::IndexType;
58
59    #[test]
60    fn parse_index_type() {
61        let str1 = "using   hash";
62        let res1 = IndexType::parse(str1);
63        assert!(res1.is_ok());
64        assert_eq!(res1.unwrap().1, IndexType::Hash);
65
66        let str2 = "USING btree   ";
67        let res2 = IndexType::parse(str2);
68        assert!(res2.is_ok());
69        assert_eq!(res2.unwrap().1, IndexType::Btree);
70    }
71}