capsid-database 0.1.0-alpha.1

The schema version check, record encoding, errors, targets, and transaction helpers that Capsid's SQLite databases share.
Documentation
use std::{fmt, str::FromStr};

use rusqlite::{
    ToSql,
    types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef},
};

use crate::{Result, StoreError};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityEpoch(uuid::Uuid);

impl AuthorityEpoch {
    pub fn generate() -> Self {
        Self(uuid::Uuid::new_v4())
    }

    pub fn uuid(&self) -> uuid::Uuid {
        self.0
    }
}

impl fmt::Display for AuthorityEpoch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

impl FromStr for AuthorityEpoch {
    type Err = StoreError;

    fn from_str(value: &str) -> Result<Self> {
        uuid::Uuid::parse_str(value)
            .map(Self)
            .map_err(StoreError::Epoch)
    }
}

impl ToSql for AuthorityEpoch {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(ToSqlOutput::from(self.0.to_string()))
    }
}

impl FromSql for AuthorityEpoch {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        uuid::Uuid::parse_str(value.as_str()?)
            .map(Self)
            .map_err(|error| FromSqlError::Other(Box::new(error)))
    }
}