1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use core::fmt;
use std::fmt::Formatter;

use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::character::complete::{multispace0, multispace1};
use nom::combinator::{map, opt};
use nom::multi::many1;
use nom::sequence::{terminated, tuple};
use nom::IResult;

use base::error::ParseSQLError;
use base::{CommonParser, DefaultOrZeroOrOne};

/// parse `ALTER {DATABASE | SCHEMA} [db_name]
///     alter_option ...`
///
/// `alter_option: {
///     [DEFAULT] CHARACTER SET [=] charset_name
///   | [DEFAULT] COLLATE [=] collation_name
///   | [DEFAULT] ENCRYPTION [=] {'Y' | 'N'}
///   | READ ONLY [=] {DEFAULT | 0 | 1}
/// }`
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct AlterDatabaseStatement {
    // we parse SQL, db_name is needed
    pub db_name: String,
    pub alter_options: Vec<AlterDatabaseOption>,
}

impl AlterDatabaseStatement {
    pub fn parse(i: &str) -> IResult<&str, AlterDatabaseStatement, ParseSQLError<&str>> {
        map(
            tuple((
                tag_no_case("ALTER"),
                multispace0,
                alt((tag_no_case("DATABASE"), tag_no_case("SCHEMA"))),
                multispace1,
                map(CommonParser::sql_identifier, String::from),
                multispace1,
                many1(terminated(AlterDatabaseOption::parse, multispace0)),
            )),
            |x| AlterDatabaseStatement {
                db_name: x.4,
                alter_options: x.6,
            },
        )(i)
    }
}

impl fmt::Display for AlterDatabaseStatement {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "ALTER DATABASE")?;
        let database = self.db_name.clone();
        write!(f, " {}", database)?;
        for alter_option in self.alter_options.iter() {
            write!(f, " {}", alter_option)?;
        }
        Ok(())
    }
}

/// `alter_option: {
///     [DEFAULT] CHARACTER SET [=] charset_name
///   | [DEFAULT] COLLATE [=] collation_name
///   | [DEFAULT] ENCRYPTION [=] {'Y' | 'N'}
///   | READ ONLY [=] {DEFAULT | 0 | 1}
/// }`
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub enum AlterDatabaseOption {
    CharacterSet(String),
    Collate(String),
    Encryption(bool),
    ReadOnly(DefaultOrZeroOrOne),
}

impl AlterDatabaseOption {
    fn parse(i: &str) -> IResult<&str, AlterDatabaseOption, ParseSQLError<&str>> {
        // [DEFAULT] CHARACTER SET [=] charset_name
        let character = map(
            tuple((
                opt(tag_no_case("DEFAULT")),
                multispace1,
                tuple((
                    tag_no_case("CHARACTER"),
                    multispace1,
                    tag_no_case("SET"),
                    multispace0,
                    opt(tag("=")),
                    multispace0,
                )),
                map(CommonParser::sql_identifier, String::from),
                multispace0,
            )),
            |(_, _, _, charset_name, _)| AlterDatabaseOption::CharacterSet(charset_name),
        );

        // [DEFAULT] COLLATE [=] collation_name
        let collate = map(
            tuple((
                opt(tag_no_case("DEFAULT")),
                multispace1,
                map(
                    tuple((
                        tag_no_case("COLLATE"),
                        multispace0,
                        opt(tag("=")),
                        multispace0,
                        CommonParser::sql_identifier,
                        multispace0,
                    )),
                    |(_, _, _, _, collation_name, _)| String::from(collation_name),
                ),
                multispace0,
            )),
            |(_, _, collation_name, _)| AlterDatabaseOption::Collate(collation_name),
        );

        // [DEFAULT] ENCRYPTION [=] {'Y' | 'N'}
        let encryption = map(
            tuple((
                opt(tag_no_case("DEFAULT")),
                multispace1,
                tag_no_case("ENCRYPTION"),
                multispace1,
                opt(tag("=")),
                multispace0,
                alt((map(tag("'Y'"), |_| true), map(tag("'N'"), |_| false))),
                multispace0,
            )),
            |x| AlterDatabaseOption::Encryption(x.6),
        );

        // READ ONLY [=] {DEFAULT | 0 | 1}
        let read_only = map(
            tuple((
                opt(tag_no_case("READ")),
                multispace1,
                tag_no_case("ONLY "),
                multispace0,
                opt(tag("=")),
                multispace0,
                DefaultOrZeroOrOne::parse,
            )),
            |x| AlterDatabaseOption::ReadOnly(x.6),
        );

        alt((character, collate, encryption, read_only))(i)
    }
}

impl fmt::Display for AlterDatabaseOption {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            AlterDatabaseOption::CharacterSet(str) => write!(f, " CHARACTER SET {}", str)?,
            AlterDatabaseOption::Collate(str) => write!(f, " COLLATE {}", str)?,
            AlterDatabaseOption::Encryption(bl) => {
                if *bl {
                    write!(f, " ENCRYPTION 'Y'",)?
                } else {
                    write!(f, " ENCRYPTION 'N'",)?
                }
            }
            AlterDatabaseOption::ReadOnly(val) => write!(f, " READ ONLY {}", val)?,
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use base::DefaultOrZeroOrOne;
    use dds::alter_database::{AlterDatabaseOption, AlterDatabaseStatement};

    #[test]
    fn test_alter_database() {
        let sqls = ["ALTER DATABASE test_db DEFAULT CHARACTER SET = utf8mb4 \
            DEFAULT COLLATE utf8mb4_unicode_ci DEFAULT ENCRYPTION = 'Y' READ ONLY = 1;"];
        let exp_statements = [AlterDatabaseStatement {
            db_name: "test_db".to_string(),
            alter_options: vec![
                AlterDatabaseOption::CharacterSet("utf8mb4".to_string()),
                AlterDatabaseOption::Collate("utf8mb4_unicode_ci".to_string()),
                AlterDatabaseOption::Encryption(true),
                AlterDatabaseOption::ReadOnly(DefaultOrZeroOrOne::One),
            ],
        }];
        for i in 0..sqls.len() {
            let res = AlterDatabaseStatement::parse(sqls[i]);
            assert!(res.is_ok());
            assert_eq!(res.unwrap().1, exp_statements[i]);
        }
    }
}