sqlparser_mysql/dds/
drop_function.rs

1use core::fmt;
2use std::fmt::Formatter;
3
4use nom::bytes::complete::tag_no_case;
5use nom::character::complete::{multispace0, multispace1};
6use nom::combinator::map;
7use nom::sequence::{terminated, tuple};
8use nom::IResult;
9
10use base::error::ParseSQLError;
11use base::CommonParser;
12
13/// parse `DROP FUNCTION [IF EXISTS] sp_name`
14#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
15pub struct DropFunctionStatement {
16    pub if_exists: bool,
17    pub sp_name: String,
18}
19
20impl DropFunctionStatement {
21    pub fn parse(i: &str) -> IResult<&str, DropFunctionStatement, ParseSQLError<&str>> {
22        map(
23            tuple((
24                terminated(tag_no_case("DROP"), multispace1),
25                terminated(tag_no_case("FUNCTION"), multispace1),
26                CommonParser::parse_if_exists,
27                map(CommonParser::sql_identifier, String::from),
28                multispace0,
29                CommonParser::statement_terminator,
30            )),
31            |x| DropFunctionStatement {
32                if_exists: x.2.is_some(),
33                sp_name: x.3,
34            },
35        )(i)
36    }
37}
38
39impl fmt::Display for DropFunctionStatement {
40    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
41        write!(f, "DROP FUNCTION")?;
42        if self.if_exists {
43            write!(f, " IF EXISTS")?;
44        }
45        write!(f, " {}", self.sp_name)?;
46        Ok(())
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use dds::drop_function::DropFunctionStatement;
53
54    #[test]
55    fn parse_drop_function() {
56        let sqls = ["DROP FUNCTION sp_name;", "DROP FUNCTION IF EXISTS sp_name;"];
57        let exp_statements = [
58            DropFunctionStatement {
59                if_exists: false,
60                sp_name: "sp_name".to_string(),
61            },
62            DropFunctionStatement {
63                if_exists: true,
64                sp_name: "sp_name".to_string(),
65            },
66        ];
67
68        for i in 0..sqls.len() {
69            let res = DropFunctionStatement::parse(sqls[i]);
70            assert!(res.is_ok());
71            assert_eq!(res.unwrap().1, exp_statements[i])
72        }
73    }
74}