use super::{RoleAttribute, UserOption, validate_name};
#[derive(Debug, Clone, Default)]
pub struct CreateUserStatement {
pub user_name: String,
pub if_not_exists: bool,
pub attributes: Vec<RoleAttribute>,
pub default_roles: Vec<String>,
pub options: Vec<UserOption>,
}
impl CreateUserStatement {
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_not_exists(mut self, flag: bool) -> Self {
self.if_not_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")?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_user_new() {
let stmt = CreateUserStatement::new();
assert!(stmt.user_name.is_empty());
assert!(!stmt.if_not_exists);
assert!(stmt.attributes.is_empty());
assert!(stmt.default_roles.is_empty());
assert!(stmt.options.is_empty());
}
#[test]
fn test_create_user_basic() {
let stmt = CreateUserStatement::new().user("app_user");
assert_eq!(stmt.user_name, "app_user");
assert!(stmt.validate().is_ok());
}
#[test]
fn test_create_user_if_not_exists() {
let stmt = CreateUserStatement::new()
.user("app_user")
.if_not_exists(true);
assert!(stmt.if_not_exists);
}
#[test]
fn test_create_user_with_attributes() {
let stmt = CreateUserStatement::new()
.user("app_user")
.attribute(RoleAttribute::Password("secret".to_string()))
.attribute(RoleAttribute::CreateDb);
assert_eq!(stmt.attributes.len(), 2);
}
#[test]
fn test_create_user_with_default_role() {
let stmt = CreateUserStatement::new()
.user("app_user@localhost")
.default_role(vec!["app_role".to_string()]);
assert_eq!(stmt.default_roles.len(), 1);
}
#[test]
fn test_create_user_with_options() {
let stmt = CreateUserStatement::new()
.user("app_user")
.option(UserOption::Comment("Test user".to_string()));
assert_eq!(stmt.options.len(), 1);
}
#[test]
fn test_create_user_validation_empty_name() {
let stmt = CreateUserStatement::new();
assert!(stmt.validate().is_err());
}
}