Files
muscl/src/core/protocol/commands/create_users.rs
h7x4 10ef171c91
All checks were successful
Build and test / check (push) Successful in 1m55s
Build and test / build (push) Successful in 2m37s
Build and test / check-license (push) Successful in 1m3s
Build and test / test (push) Successful in 3m6s
Build and test / docs (push) Successful in 5m56s
client: print errors and warnings to stderr
2025-12-16 17:21:58 +09:00

88 lines
2.5 KiB
Rust

use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::json;
use thiserror::Error;
use crate::core::{
protocol::request_validation::ValidationError,
types::{DbOrUser, MySQLUser},
};
pub type CreateUsersRequest = Vec<MySQLUser>;
pub type CreateUsersResponse = BTreeMap<MySQLUser, Result<(), CreateUserError>>;
#[derive(Error, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CreateUserError {
#[error("Validation error: {0}")]
ValidationError(#[from] ValidationError),
#[error("User already exists")]
UserAlreadyExists,
#[error("MySQL error: {0}")]
MySqlError(String),
}
pub fn print_create_users_output_status(output: &CreateUsersResponse) {
for (username, result) in output {
match result {
Ok(()) => {
println!("User '{}' created successfully.", username);
}
Err(err) => {
eprintln!("{}", err.to_error_message(username));
eprintln!("Skipping...");
}
}
println!();
}
}
pub fn print_create_users_output_status_json(output: &CreateUsersResponse) {
let value = output
.iter()
.map(|(name, result)| match result {
Ok(()) => (name.to_string(), json!({ "status": "success" })),
Err(err) => (
name.to_string(),
json!({
"status": "error",
"type": err.error_type(),
"error": err.to_error_message(name),
}),
),
})
.collect::<serde_json::Map<_, _>>();
println!(
"{}",
serde_json::to_string_pretty(&value)
.unwrap_or("Failed to serialize result to JSON".to_string())
);
}
impl CreateUserError {
pub fn to_error_message(&self, username: &MySQLUser) -> String {
match self {
CreateUserError::ValidationError(err) => {
err.to_error_message(DbOrUser::User(username.clone()))
}
CreateUserError::UserAlreadyExists => {
format!("User '{}' already exists.", username)
}
CreateUserError::MySqlError(err) => {
format!("MySQL error: {}", err)
}
}
}
pub fn error_type(&self) -> String {
match self {
CreateUserError::ValidationError(err) => err.error_type(),
CreateUserError::UserAlreadyExists => "user-already-exists".to_string(),
CreateUserError::MySqlError(_) => "mysql-error".to_string(),
}
}
}