rjango 0.1.1

A full-stack Rust backend framework inspired by Django
Documentation
use crate::core::validators::{ProhibitNullCharactersValidator, ValidationError, Validator};

use super::FieldType;

pub fn validate_text_field(value: &str) -> Result<(), ValidationError> {
    ProhibitNullCharactersValidator::default().validate(&value)
}

#[must_use]
pub fn db_type(field: &FieldType, vendor: &str) -> Option<String> {
    match field {
        FieldType::Text => Some(match vendor {
            "mysql" => "longtext".to_string(),
            _ => "text".to_string(),
        }),
        _ => None,
    }
}

pub fn get_prep_value(value: &str) -> Result<String, ValidationError> {
    validate_text_field(value)?;
    Ok(value.to_string())
}

pub fn from_db_value(value: &str) -> Result<String, ValidationError> {
    validate_text_field(value)?;
    Ok(value.to_string())
}

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

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

    #[test]
    fn db_type_for_mysql_uses_longtext() {
        assert_eq!(
            db_type(&FieldType::Text, "mysql").as_deref(),
            Some("longtext")
        );
    }

    #[test]
    fn get_prep_value_keeps_text_intact() {
        let prepared =
            get_prep_value("hello world").expect("text preparation should keep valid text");
        assert_eq!(prepared, "hello world");
    }

    #[test]
    fn from_db_value_returns_identity() {
        let value = from_db_value("stored body").expect("stored text should round-trip");
        assert_eq!(value, "stored body");
    }

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