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 capsid_model::{
    BackupId, CheckpointId, InstanceId, JobGroupId, JobRunId, LedgerId, NetworkId, PoolId,
    ProjectId, RequestId, RevisionId, TemplateId, TokenId, VolumeId, WorkloadId, WorkspaceId,
};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target<Id> {
    Id(Id),
    // Not a `capsid_model::Name`: a lookup only compares against names the
    // store validated when it wrote them, so an invalid one is simply not found.
    Name(String),
}

impl<Id: FromStr> Target<Id> {
    pub fn parse(target: &str) -> Self {
        match target.parse() {
            Ok(id) => Self::Id(id),
            Err(_) => Self::Name(target.to_owned()),
        }
    }
}

impl<Id: PartialEq> Target<Id> {
    // Whether this target selects what an earlier request selected as
    // `original` and resolved to `id`.
    pub fn matches(&self, id: &Id, original: &str) -> bool {
        match self {
            Self::Id(target) => target == id,
            Self::Name(name) => name == original,
        }
    }
}

impl<Id: fmt::Display> fmt::Display for Target<Id> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Id(id) => id.fmt(formatter),
            Self::Name(name) => formatter.write_str(name),
        }
    }
}

impl<Id: Clone> From<&Target<Id>> for Target<Id> {
    fn from(target: &Target<Id>) -> Self {
        target.clone()
    }
}

// A blanket `From<Id>` would overlap with `From<&str>`, so each target type is listed.
macro_rules! target {
    ($($id:ty),+ $(,)?) => {$(
        impl From<$id> for Target<$id> {
            fn from(id: $id) -> Self {
                Self::Id(id)
            }
        }

        impl From<&$id> for Target<$id> {
            fn from(id: &$id) -> Self {
                Self::Id(*id)
            }
        }

        impl From<&str> for Target<$id> {
            fn from(target: &str) -> Self {
                Self::parse(target)
            }
        }

        impl From<&String> for Target<$id> {
            fn from(target: &String) -> Self {
                Self::parse(target)
            }
        }

        impl From<String> for Target<$id> {
            fn from(target: String) -> Self {
                Self::parse(&target)
            }
        }
    )+};
}

target!(
    BackupId,
    CheckpointId,
    InstanceId,
    JobGroupId,
    JobRunId,
    LedgerId,
    NetworkId,
    PoolId,
    ProjectId,
    RequestId,
    RevisionId,
    TemplateId,
    TokenId,
    VolumeId,
    WorkloadId,
    WorkspaceId,
);