rjango 0.1.1

A full-stack Rust backend framework inspired by Django
Documentation
use uuid::Uuid;

use crate::core::validators::ValidationError;

use super::FieldType;

pub fn validate_uuid_field(value: &str) -> Result<Uuid, ValidationError> {
    Uuid::parse_str(value).map_err(|_| {
        ValidationError::new("Enter a valid UUID.", "invalid").with_param("value", value)
    })
}

#[must_use]
pub fn db_type(field: &FieldType, vendor: &str) -> Option<String> {
    match field {
        FieldType::Uuid => Some(match vendor {
            "postgres" => "uuid".to_string(),
            "sqlite" | "mysql" => "char(32)".to_string(),
            _ => "uuid".to_string(),
        }),
        _ => None,
    }
}

pub fn get_prep_value(value: &str, vendor: &str) -> Result<String, ValidationError> {
    let parsed = validate_uuid_field(value)?;
    Ok(match vendor {
        "postgres" => parsed.hyphenated().to_string(),
        "sqlite" | "mysql" => parsed.simple().to_string(),
        _ => parsed.hyphenated().to_string(),
    })
}

pub fn from_db_value(value: &str) -> Result<String, ValidationError> {
    validate_uuid_field(value).map(|parsed| parsed.hyphenated().to_string())
}

#[must_use]
pub fn formfield(field: &FieldType) -> Option<&'static str> {
    match field {
        FieldType::Uuid => Some("CharField"),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::{FieldType, db_type, formfield, from_db_value, get_prep_value};

    #[test]
    fn db_type_for_postgres_uses_native_uuid() {
        assert_eq!(
            db_type(&FieldType::Uuid, "postgres").as_deref(),
            Some("uuid")
        );
    }

    #[test]
    fn get_prep_value_normalizes_sqlite_uuid_without_hyphens() {
        let prepared = get_prep_value("550e8400-e29b-41d4-a716-446655440000", "sqlite")
            .expect("uuid preparation should normalize valid UUIDs");
        assert_eq!(prepared, "550e8400e29b41d4a716446655440000");
    }

    #[test]
    fn from_db_value_parses_compact_uuid() {
        let parsed = from_db_value("550e8400e29b41d4a716446655440000")
            .expect("compact UUIDs should parse from storage");
        assert_eq!(parsed, "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn formfield_returns_correct_type() {
        assert_eq!(formfield(&FieldType::Uuid), Some("CharField"));
    }
}