use crate::models::Column;
pub struct Rules;
impl Rules {
pub fn from_column(column: &Column) -> Vec<String> {
let mut rules = vec![];
if !column.has_modifier("nullable") {
rules.push("required".to_string());
} else {
rules.push("nullable".to_string());
}
match column.data_type.as_str() {
"string" | "char" => {
rules.push("string".to_string());
if let Some(attr) = column.attributes.first() {
if let Ok(max) = attr.parse::<usize>() {
rules.push(format!("max:{}", max));
}
}
}
"text" | "longtext" | "mediumtext" => {
rules.push("string".to_string());
}
"integer" | "bigInteger" | "smallInteger" | "tinyInteger" | "mediumInteger" => {
rules.push("integer".to_string());
}
"unsignedInteger" | "unsignedBigInteger" | "unsignedSmallInteger"
| "unsignedTinyInteger" | "unsignedMediumInteger" => {
rules.push("integer".to_string());
}
"boolean" => {
rules.push("boolean".to_string());
}
"float" | "double" => {
rules.push("numeric".to_string());
}
"decimal" => {
rules.push("numeric".to_string());
}
"date" => {
rules.push("date".to_string());
}
"datetime" | "timestamp" | "datetimeTz" | "timestampTz" => {
rules.push("date".to_string());
}
"email" => {
rules.push("email".to_string());
}
"ipAddress" => {
rules.push("ip".to_string());
}
"macAddress" => {
rules.push("regex:/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/".to_string());
}
"url" => {
rules.push("url".to_string());
}
"uuid" => {
rules.push("uuid".to_string());
}
"ulid" => {
rules.push("string".to_string());
}
"json" | "jsonb" => {
rules.push("json".to_string());
}
"enum" => {
rules.push("string".to_string());
if !column.attributes.is_empty() {
let values: Vec<String> = column.attributes
.iter()
.flat_map(|a| a.split(','))
.map(|v| v.trim().to_string())
.collect();
rules.push(format!("in:{}", values.join(",")));
}
}
_ => {}
}
if column.has_modifier("unique") {
rules.push(format!("unique:{}", column.name));
}
rules
}
}