cql3_parser/
role_common.rs

1use crate::common::Identifier;
2use itertools::Itertools;
3use std::fmt::{Display, Formatter};
4
5/// the data for the `create role` statement.
6#[derive(PartialEq, Debug, Clone)]
7pub struct RoleCommon {
8    /// the name of the role
9    pub name: Identifier,
10    /// if specified the password for the role
11    pub password: Option<String>,
12    /// if specified then the user is explicitly noted as `SUPERUER` or `NOSUPERUSER`
13    pub superuser: Option<bool>,
14    /// if specified the user LOGIN option is specified
15    pub login: Option<bool>,
16    /// the list of options for an external authenticator.
17    pub options: Vec<(String, String)>,
18    /// only create the role if it does not exist.
19    pub if_not_exists: bool,
20}
21
22impl Display for RoleCommon {
23    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
24        let mut with = vec![];
25
26        if let Some(password) = &self.password {
27            with.push(format!("PASSWORD = {}", password));
28        }
29        if let Some(superuser) = self.superuser {
30            with.push(format!(
31                "SUPERUSER = {}",
32                if superuser { "TRUE" } else { "FALSE" }
33            ));
34        }
35        if let Some(login) = self.login {
36            with.push(format!("LOGIN = {}", if login { "TRUE" } else { "FALSE" }));
37        }
38        if !self.options.is_empty() {
39            let mut txt = "OPTIONS = {".to_string();
40            txt.push_str(
41                self.options
42                    .iter()
43                    .map(|(x, y)| format!("{}:{}", x, y))
44                    .join(", ")
45                    .as_str(),
46            );
47            txt.push('}');
48            with.push(txt.to_string());
49        }
50        if with.is_empty() {
51            write!(
52                f,
53                "ROLE {}{}",
54                if self.if_not_exists {
55                    "IF NOT EXISTS "
56                } else {
57                    ""
58                },
59                self.name
60            )
61        } else {
62            write!(
63                f,
64                "ROLE {}{} WITH {}",
65                if self.if_not_exists {
66                    "IF NOT EXISTS "
67                } else {
68                    ""
69                },
70                self.name,
71                with.iter().join(" AND ")
72            )
73        }
74    }
75}