rjango 0.1.1

A full-stack Rust backend framework inspired by Django
Documentation
use super::mixins::{FieldCacheMixin, FieldValidationMixin};
use crate::utils::dateparse::parse_duration;

/// A DurationField stores elapsed time values as database durations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DurationField {
    pub store_microseconds: bool,
}

impl Default for DurationField {
    fn default() -> Self {
        Self {
            store_microseconds: true,
        }
    }
}

impl DurationField {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn store_microseconds(&self) -> bool {
        self.store_microseconds
    }

    #[must_use]
    pub fn db_type(&self) -> &str {
        "BIGINT"
    }
}

impl FieldCacheMixin for DurationField {
    fn get_cache_name(&self) -> String {
        "duration_field".to_string()
    }

    fn is_cached(&self) -> bool {
        false
    }
}

impl FieldValidationMixin for DurationField {
    fn validate(&self, value: &str) -> Result<(), String> {
        parse_duration(value)
            .map(|_| ())
            .ok_or_else(|| "Enter a valid duration.".to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::DurationField;

    #[test]
    fn duration_field_defaults_to_microsecond_storage() {
        let field = DurationField::default();

        assert!(field.store_microseconds());
    }

    #[test]
    fn duration_field_reports_bigint_db_type() {
        let field = DurationField::new();

        assert_eq!(field.db_type(), "BIGINT");
    }
}