sqlparser_mysql/base/
lock_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::tuple;
6use nom::IResult;
7use std::fmt::{Display, Formatter};
8
9use base::ParseSQLError;
10
11/// lock_option:
12///     parse `LOCK [=] {DEFAULT | NONE | SHARED | EXCLUSIVE}`
13#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
14pub enum LockType {
15    Default,
16    None,
17    Shared,
18    Exclusive,
19}
20
21impl Display for LockType {
22    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
23        match *self {
24            LockType::Default => write!(f, "LOCK DEFAULT"),
25            LockType::None => write!(f, "LOCK NONE"),
26            LockType::Shared => write!(f, "LOCK SHARED"),
27            LockType::Exclusive => write!(f, "LOCK EXCLUSIVE"),
28        }
29    }
30}
31
32impl LockType {
33    pub fn parse(i: &str) -> IResult<&str, LockType, ParseSQLError<&str>> {
34        alt((
35            map(
36                tuple((tag_no_case("LOCK"), multispace1, Self::parse_lock)),
37                |(_, _, lock)| lock,
38            ),
39            map(
40                tuple((
41                    tag_no_case("LOCK"),
42                    multispace0,
43                    tag("="),
44                    multispace0,
45                    Self::parse_lock,
46                )),
47                |(_, _, _, _, lock)| lock,
48            ),
49        ))(i)
50    }
51
52    fn parse_lock(i: &str) -> IResult<&str, LockType, ParseSQLError<&str>> {
53        alt((
54            map(tag_no_case("DEFAULT"), |_| LockType::Default),
55            map(tag_no_case("NONE"), |_| LockType::None),
56            map(tag_no_case("SHARED"), |_| LockType::Shared),
57            map(tag_no_case("EXCLUSIVE"), |_| LockType::Exclusive),
58        ))(i)
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use base::lock_type::LockType;
65
66    #[test]
67    fn parse_lock_type() {
68        let str1 = "LOCK EXCLUSIVE";
69        let res1 = LockType::parse(str1);
70        assert!(res1.is_ok());
71        assert_eq!(res1.unwrap().1, LockType::Exclusive);
72
73        let str2 = "lock=DEFAULT";
74        let res2 = LockType::parse(str2);
75        assert!(res2.is_ok());
76        assert_eq!(res2.unwrap().1, LockType::Default);
77
78        let str3 = "LOCK= NONE";
79        let res3 = LockType::parse(str3);
80        assert!(res3.is_ok());
81        assert_eq!(res3.unwrap().1, LockType::None);
82
83        let str4 = "lock =SHARED";
84        let res4 = LockType::parse(str4);
85        assert!(res4.is_ok());
86        assert_eq!(res4.unwrap().1, LockType::Shared);
87
88        let str5 = "lockSHARED";
89        let res5 = LockType::parse(str5);
90        assert!(res5.is_err());
91    }
92}