sea-orm-relations-kit 0.1.0

Laravel-style relations for SeaORM: polymorphic relations, many-to-many attach/sync/toggle, relation counts and latest-of-many
Documentation
//! Keys: the value that links a row to its owner, in a form that can be hashed and
//! compared whatever integer width or string type each table uses for it.

use sea_orm::{
    sea_query::ColumnType, ColumnTrait, DbErr, EntityName, EntityTrait, Iterable, ModelTrait,
    PrimaryKeyToColumn, QueryResult, Value,
};

/// A primary key value, normalized.
///
/// `posts.id` may be `INTEGER` while `comments.commentable_id` is `BIGINT` or even
/// `VARCHAR`; all three hold the same key. `Key` lets the crate match them up and
/// write a key into any of those columns.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Key {
    /// Any integer key.
    Int(i64),
    /// A string key, such as a UUID or a slug.
    Text(String),
}

impl Key {
    /// The primary key of `model`.
    ///
    /// # Panics
    ///
    /// If the entity has a composite primary key; relations here link single keys.
    #[must_use]
    pub fn of<M: ModelTrait>(model: &M) -> Option<Self> {
        Self::from_value(&model.get(primary_column::<M::Entity>()))
    }

    /// The key a column value holds, or `None` for `NULL` and types that are not keys.
    ///
    /// A string holding a canonical integer (`"15"`, not `"015"`) becomes
    /// [`Key::Int`], so a `VARCHAR` morph column matches an integer primary key.
    #[must_use]
    pub fn from_value(value: &Value) -> Option<Self> {
        match value {
            Value::TinyInt(Some(v)) => Some(Self::Int(i64::from(*v))),
            Value::SmallInt(Some(v)) => Some(Self::Int(i64::from(*v))),
            Value::Int(Some(v)) => Some(Self::Int(i64::from(*v))),
            Value::BigInt(Some(v)) => Some(Self::Int(*v)),
            Value::TinyUnsigned(Some(v)) => Some(Self::Int(i64::from(*v))),
            Value::SmallUnsigned(Some(v)) => Some(Self::Int(i64::from(*v))),
            Value::Unsigned(Some(v)) => Some(Self::Int(i64::from(*v))),
            Value::BigUnsigned(Some(v)) => i64::try_from(*v).ok().map(Self::Int),
            Value::String(Some(v)) => Some(Self::from_text(v.clone())),
            Value::Char(Some(v)) => Some(Self::from_text(v.to_string())),
            #[cfg(feature = "with-uuid")]
            Value::Uuid(Some(v)) => Some(Self::Text(v.to_string())),
            _ => None,
        }
    }

    fn from_text(text: String) -> Self {
        match text.parse::<i64>() {
            Ok(number) if number.to_string() == text => Self::Int(number),
            _ => Self::Text(text),
        }
    }

    /// This key as a value of the type `column` stores, ready to be written to it
    /// or compared with it.
    ///
    /// # Errors
    ///
    /// When the key does not fit: a negative key in an unsigned column, a word in an
    /// integer column, a non-UUID in a UUID column.
    pub fn to_value_for<C: ColumnTrait>(&self, column: C) -> Result<Value, DbErr> {
        let column_type = column.def().get_column_type().clone();
        let mismatch = || {
            DbErr::Type(format!(
                "the key {self} does not fit the {column_type:?} column {}",
                column.as_str()
            ))
        };
        let value = match (self, &column_type) {
            (Self::Int(v), ColumnType::TinyInteger) => {
                Value::TinyInt(Some(i8::try_from(*v).map_err(|_| mismatch())?))
            }
            (Self::Int(v), ColumnType::SmallInteger) => {
                Value::SmallInt(Some(i16::try_from(*v).map_err(|_| mismatch())?))
            }
            (Self::Int(v), ColumnType::Integer) => {
                Value::Int(Some(i32::try_from(*v).map_err(|_| mismatch())?))
            }
            (Self::Int(v), ColumnType::BigInteger) => Value::BigInt(Some(*v)),
            (Self::Int(v), ColumnType::TinyUnsigned) => {
                Value::TinyUnsigned(Some(u8::try_from(*v).map_err(|_| mismatch())?))
            }
            (Self::Int(v), ColumnType::SmallUnsigned) => {
                Value::SmallUnsigned(Some(u16::try_from(*v).map_err(|_| mismatch())?))
            }
            (Self::Int(v), ColumnType::Unsigned) => {
                Value::Unsigned(Some(u32::try_from(*v).map_err(|_| mismatch())?))
            }
            (Self::Int(v), ColumnType::BigUnsigned) => {
                Value::BigUnsigned(Some(u64::try_from(*v).map_err(|_| mismatch())?))
            }
            (_, ColumnType::String(_) | ColumnType::Text | ColumnType::Char(_)) => {
                Value::String(Some(self.to_string()))
            }
            #[cfg(feature = "with-uuid")]
            (Self::Text(v), ColumnType::Uuid) => Value::Uuid(Some(
                sea_orm::prelude::Uuid::parse_str(v).map_err(|_| mismatch())?,
            )),
            _ => return Err(mismatch()),
        };
        Ok(value)
    }

    /// Reads a key from a raw query result, whatever type the column has.
    pub(crate) fn read(row: &QueryResult, column: &str) -> Result<Self, DbErr> {
        let found = row
            .try_get::<Option<i64>>("", column)
            .map(|v| v.map(Self::Int))
            .or_else(|_| {
                row.try_get::<Option<i32>>("", column)
                    .map(|v| v.map(|v| Self::Int(v.into())))
            })
            .or_else(|_| {
                row.try_get::<Option<i16>>("", column)
                    .map(|v| v.map(|v| Self::Int(v.into())))
            })
            .or_else(|_| {
                row.try_get::<Option<u32>>("", column)
                    .map(|v| v.map(|v| Self::Int(v.into())))
            })
            .or_else(|_| {
                row.try_get::<Option<u64>>("", column)
                    .map(|v| v.and_then(|v| i64::try_from(v).ok()).map(Self::Int))
            })
            .or_else(|_| {
                row.try_get::<Option<String>>("", column)
                    .map(|v| v.map(Self::from_text))
            });
        #[cfg(feature = "with-uuid")]
        let found = found.or_else(|_| {
            row.try_get::<Option<sea_orm::prelude::Uuid>>("", column)
                .map(|v| v.map(|v| Self::Text(v.to_string())))
        });
        found?.ok_or_else(|| DbErr::Type(format!("the key column {column} is NULL")))
    }
}

impl std::fmt::Display for Key {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Int(v) => write!(f, "{v}"),
            Self::Text(v) => f.write_str(v),
        }
    }
}

macro_rules! key_from_int {
    ($($t:ty),+) => {$(
        impl From<$t> for Key {
            fn from(value: $t) -> Self {
                Self::Int(i64::from(value))
            }
        }
    )+};
}

key_from_int!(i8, i16, i32, i64, u8, u16, u32);

impl From<&str> for Key {
    fn from(value: &str) -> Self {
        Self::from_text(value.to_string())
    }
}

impl From<String> for Key {
    fn from(value: String) -> Self {
        Self::from_text(value)
    }
}

impl From<&Self> for Key {
    fn from(value: &Self) -> Self {
        value.clone()
    }
}

#[cfg(feature = "with-uuid")]
impl From<sea_orm::prelude::Uuid> for Key {
    fn from(value: sea_orm::prelude::Uuid) -> Self {
        Self::Text(value.to_string())
    }
}

/// The single primary key column of `E`.
///
/// # Panics
///
/// If the entity has a composite primary key.
pub fn primary_column<E: EntityTrait>() -> E::Column {
    let mut keys = E::PrimaryKey::iter();
    let first = keys.next().expect("every SeaORM entity has a primary key");
    assert!(
        keys.next().is_none(),
        "sea-orm-relations-kit links single-column primary keys only, and `{}` has a composite one",
        E::default().table_name()
    );
    first.into_column()
}

/// The primary key of `model`, which must not be `NULL`.
pub fn require_key<M: ModelTrait>(model: &M) -> Result<Key, DbErr> {
    let value = model.get(primary_column::<M::Entity>());
    key_or_error(&value, M::Entity::default().table_name())
}

/// The key `value` holds, or an error saying why there is none.
pub fn key_or_error(value: &Value, table: &str) -> Result<Key, DbErr> {
    Key::from_value(value).ok_or_else(|| {
        if value.is_some() {
            DbErr::Type(format!(
                "a `{table}` key of type {value:?} is not supported; UUID keys need the `with-uuid` feature of sea-orm-relations-kit"
            ))
        } else {
            DbErr::Type(format!("a `{table}` row has a NULL key"))
        }
    })
}

/// `keys` converted for `column`, with duplicates dropped and the order kept.
pub fn values_for<C: ColumnTrait>(keys: &[Key], column: C) -> Result<Vec<Value>, DbErr> {
    let mut seen = std::collections::HashSet::new();
    keys.iter()
        .filter(|key| seen.insert(*key))
        .map(|key| key.to_value_for(column))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::Key;
    use sea_orm::Value;

    #[test]
    fn integers_of_every_width_are_one_key() {
        assert_eq!(Key::from_value(&Value::Int(Some(15))), Some(Key::Int(15)));
        assert_eq!(
            Key::from_value(&Value::BigInt(Some(15))),
            Some(Key::Int(15))
        );
        assert_eq!(
            Key::from_value(&Value::SmallUnsigned(Some(15))),
            Some(Key::Int(15))
        );
    }

    #[test]
    fn a_numeric_string_matches_an_integer_key() {
        assert_eq!(
            Key::from_value(&Value::String(Some("15".into()))),
            Some(Key::Int(15))
        );
        assert_eq!(
            Key::from_value(&Value::String(Some("015".into()))),
            Some(Key::Text("015".into()))
        );
        assert_eq!(Key::from("abc"), Key::Text("abc".into()));
    }

    #[test]
    fn null_and_non_key_values_are_no_key() {
        assert_eq!(Key::from_value(&Value::Int(None)), None);
        assert_eq!(Key::from_value(&Value::Bool(Some(true))), None);
        assert_eq!(Key::from_value(&Value::BigUnsigned(Some(u64::MAX))), None);
    }
}