use super::{RoleAttribute, UserOption, validate_name};
#[derive(Debug, Clone, Default)]
pub struct AlterUserStatement {
pub user_name: String,
pub if_exists: bool,
pub attributes: Vec<RoleAttribute>,
pub default_roles: Vec<String>,
pub options: Vec<UserOption>,
}
impl AlterUserStatement {
pub fn new() -> Self {
Self::default()
}
pub fn user(mut self, name: impl Into<String>) -> Self {
self.user_name = name.into();
self
}
pub fn if_exists(mut self, flag: bool) -> Self {
self.if_exists = flag;
self
}
pub fn attribute(mut self, attr: RoleAttribute) -> Self {
self.attributes.push(attr);
self
}
pub fn attributes(mut self, attrs: Vec<RoleAttribute>) -> Self {
self.attributes = attrs;
self
}
pub fn default_role(mut self, roles: Vec<String>) -> Self {
self.default_roles = roles;
self
}
pub fn option(mut self, opt: UserOption) -> Self {
self.options.push(opt);
self
}
pub fn options(mut self, opts: Vec<UserOption>) -> Self {
self.options = opts;
self
}
pub fn validate(&self) -> Result<(), String> {
validate_name(&self.user_name, "User name")?;
if self.attributes.is_empty() && self.default_roles.is_empty() && self.options.is_empty() {
return Err(
"At least one attribute, default role, or option must be specified".to_string(),
);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_alter_user_new() {
let stmt = AlterUserStatement::new();
assert!(stmt.user_name.is_empty());
assert!(!stmt.if_exists);
assert!(stmt.attributes.is_empty());
assert!(stmt.default_roles.is_empty());
assert!(stmt.options.is_empty());
}
#[test]
fn test_alter_user_basic() {
let stmt = AlterUserStatement::new()
.user("app_user")
.attribute(RoleAttribute::Login);
assert_eq!(stmt.user_name, "app_user");
assert!(stmt.validate().is_ok());
}
#[test]
fn test_alter_user_if_exists() {
let stmt = AlterUserStatement::new().user("app_user").if_exists(true);
assert!(stmt.if_exists);
}
#[test]
fn test_alter_user_with_attributes() {
let stmt = AlterUserStatement::new()
.user("app_user")
.attribute(RoleAttribute::Password("new_secret".to_string()))
.attribute(RoleAttribute::CreateDb);
assert_eq!(stmt.attributes.len(), 2);
}
#[test]
fn test_alter_user_with_default_role() {
let stmt = AlterUserStatement::new()
.user("app_user@localhost")
.default_role(vec!["app_role".to_string()]);
assert_eq!(stmt.default_roles.len(), 1);
}
#[test]
fn test_alter_user_with_options() {
let stmt = AlterUserStatement::new()
.user("app_user")
.option(UserOption::AccountUnlock);
assert_eq!(stmt.options.len(), 1);
}
#[test]
fn test_alter_user_validation_empty_name() {
let stmt = AlterUserStatement::new();
assert!(stmt.validate().is_err());
}
}