sea-orm-taggable 0.1.1

Tags for any SeaORM entity: attach, detach, sync, tag types, ordering and tag filters
Documentation
//! The `tags` table: a tag, its slug, an optional type and its position in the list.

use chrono::Utc;
use sea_orm::{
    entity::prelude::*,
    sea_query::{Expr, ExprTrait, Func},
    ActiveValue::Set,
    Condition, QueryOrder, QuerySelect,
};
use sea_orm_relations_kit::Key;
use sea_orm_sluggable::{SlugConfig, Sluggable};

use crate::{Taggable, TAGS};

/// A tag.
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "tags")]
pub struct Model {
    /// The primary key.
    #[sea_orm(primary_key)]
    pub id: i64,
    /// The name as written: `"Rust"`, `"SeaORM"`.
    pub name: String,
    /// The name made URL-safe, unique among tags of the same type.
    pub slug: String,
    /// A group of tags, such as `"topic"` or `"language"`; `None` for plain tags.
    #[sea_orm(column_name = "type")]
    pub tag_type: Option<String>,
    /// The position among tags of the same type, from 1.
    pub order_column: i32,
    /// When the tag was created.
    pub created_at: DateTimeWithTimeZone,
    /// When the tag was last changed.
    pub updated_at: DateTimeWithTimeZone,
}

/// The tag's relations.
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
    /// The pivot rows linking this tag to tagged rows.
    #[sea_orm(has_many = "super::taggable::Entity")]
    Taggables,
}

impl Related<super::taggable::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::Taggables.def()
    }
}

impl Sluggable for ActiveModel {
    fn slug_config() -> SlugConfig<Self> {
        SlugConfig::new([Column::Name], Column::Slug)
            .on_update(true)
            .scope(|tag: &Self| of_type(tag.tag_type.try_as_ref().cloned().flatten().as_deref()))
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
        let mut tag = sea_orm_sluggable::fill_slug(self, db, insert).await?;
        let now = Utc::now().fixed_offset();
        let tag_type = tag.tag_type.try_as_ref().cloned().flatten();
        if insert {
            tag.created_at = Set(now);
            if tag.order_column.is_not_set() {
                tag.order_column = Set(last_position(db, tag_type.as_deref()).await? + 1);
            }
        } else if tag.tag_type.is_set()
            && !tag.order_column.is_set()
            && moved_type(db, &tag, tag_type.as_deref()).await?
        {
            // A tag moved to another type goes last there, not onto a taken position.
            tag.order_column = Set(last_position(db, tag_type.as_deref()).await? + 1);
        }
        tag.updated_at = Set(now);
        Ok(tag)
    }
}

/// `type = tag_type`, or `type IS NULL` for plain tags.
pub(crate) fn of_type(tag_type: Option<&str>) -> Condition {
    let column = Column::TagType;
    Condition::all().add(tag_type.map_or_else(|| column.is_null(), |tag_type| column.eq(tag_type)))
}

/// `lower(name) = lower(text) OR slug = text`: a tag as people refer to it.
/// The name is compared ignoring case, so "RUST" finds "Rust".
pub(crate) fn named(text: &str) -> Condition {
    let text = text.trim();
    Condition::any()
        .add(Expr::expr(Func::lower(Expr::col(Column::Name))).eq(text.to_lowercase()))
        .add(Column::Slug.eq(text))
}

/// Whether the stored tag has another type than `tag_type`.
async fn moved_type<C: ConnectionTrait>(
    db: &C,
    tag: &ActiveModel,
    tag_type: Option<&str>,
) -> Result<bool, DbErr> {
    let Some(id) = tag.id.try_as_ref() else {
        return Ok(false);
    };
    let stored = Entity::find_by_id(*id).one(db).await?;
    Ok(stored.is_some_and(|stored| stored.tag_type.as_deref() != tag_type))
}

/// The highest position among tags of `tag_type`, `0` when there are none.
async fn last_position<C: ConnectionTrait>(db: &C, tag_type: Option<&str>) -> Result<i32, DbErr> {
    let last: Option<Option<i32>> = Entity::find()
        .select_only()
        .column_as(Expr::col(Column::OrderColumn).max(), "last")
        .filter(of_type(tag_type))
        .into_tuple()
        .one(db)
        .await?;
    Ok(last.flatten().unwrap_or(0))
}

impl Entity {
    /// The tags with these names (or slugs) and type, creating the missing ones, in
    /// the order of `names`.
    ///
    /// # Errors
    ///
    /// On a database error, or when a name has no letters or digits to make a slug.
    pub async fn find_or_create<C, S>(
        db: &C,
        names: impl IntoIterator<Item = S> + Send,
        tag_type: Option<&str>,
    ) -> Result<Vec<Model>, DbErr>
    where
        C: ConnectionTrait,
        S: AsRef<str> + Send,
    {
        let mut tags = Vec::new();
        for name in names {
            let name = name.as_ref().trim();
            let tag = match Self::find_from_string(db, name, tag_type).await? {
                Some(tag) => tag,
                None => {
                    ActiveModel {
                        name: Set(name.to_string()),
                        tag_type: Set(tag_type.map(str::to_string)),
                        ..Default::default()
                    }
                    .insert(db)
                    .await?
                }
            };
            if !tags.iter().any(|seen: &Model| seen.id == tag.id) {
                tags.push(tag);
            }
        }
        Ok(tags)
    }

    /// The tag of this type whose name or slug is `name`.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn find_from_string<C: ConnectionTrait>(
        db: &C,
        name: &str,
        tag_type: Option<&str>,
    ) -> Result<Option<Model>, DbErr> {
        Self::find()
            .filter(named(name.trim()))
            .filter(of_type(tag_type))
            .order_by_asc(Column::Id)
            .one(db)
            .await
    }

    /// The tags of this type whose name or slug is one of `names`, in tag order.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn find_many_from_string<C, S>(
        db: &C,
        names: impl IntoIterator<Item = S> + Send,
        tag_type: Option<&str>,
    ) -> Result<Vec<Model>, DbErr>
    where
        C: ConnectionTrait,
        S: AsRef<str> + Send,
    {
        let any_name = names.into_iter().fold(Condition::any(), |any, name| {
            any.add(named(name.as_ref().trim()))
        });
        Self::with_type(tag_type).filter(any_name).all(db).await
    }

    /// The tags of any type whose name or slug is `name`.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn find_from_string_of_any_type<C: ConnectionTrait>(
        db: &C,
        name: &str,
    ) -> Result<Vec<Model>, DbErr> {
        Self::ordered().filter(named(name.trim())).all(db).await
    }

    /// All tags, by type and position.
    #[must_use]
    pub fn ordered() -> Select<Self> {
        Self::find()
            .order_by_asc(Column::TagType)
            .order_by_asc(Column::OrderColumn)
            .order_by_asc(Column::Id)
    }

    /// The tags of one type (`None` for plain tags), by position.
    #[must_use]
    pub fn with_type(tag_type: Option<&str>) -> Select<Self> {
        Self::ordered().filter(of_type(tag_type))
    }

    /// Tags whose name contains `text`, ignoring case: for autocomplete.
    #[must_use]
    pub fn containing(text: &str) -> Select<Self> {
        let pattern = format!("%{}%", escape_like(&text.to_lowercase()));
        Self::ordered().filter(
            Expr::expr(Func::lower(Expr::col(Column::Name)))
                .like(sea_orm::sea_query::LikeExpr::new(pattern).escape('\\')),
        )
    }

    /// The types in use, sorted, without plain tags' `None`.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn types<C: ConnectionTrait>(db: &C) -> Result<Vec<String>, DbErr> {
        Self::find()
            .select_only()
            .column(Column::TagType)
            .filter(Column::TagType.is_not_null())
            .distinct()
            .order_by_asc(Column::TagType)
            .into_tuple()
            .all(db)
            .await
    }

    /// Puts the tags with `ids` at positions 1, 2, 3 ... in that order. Tags not
    /// listed keep their positions.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn set_new_order<C: ConnectionTrait>(
        db: &C,
        ids: impl IntoIterator<Item = i64> + Send,
    ) -> Result<(), DbErr> {
        for (position, id) in (1..).zip(ids) {
            Self::update_many()
                .col_expr(Column::OrderColumn, Expr::value(position))
                .filter(Column::Id.eq(id))
                .exec(db)
                .await?;
        }
        Ok(())
    }
}

impl Model {
    /// The rows of type `O` carrying this tag, ready to filter and run.
    ///
    /// # Errors
    ///
    /// Never in practice: a loaded tag always has a key.
    pub fn tagged<O: Taggable>(&self) -> Result<Select<O>, DbErr> {
        TAGS.owners_of::<O>(self)
    }

    /// Swaps positions with the previous tag of the same type; nothing at the top.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn move_order_up<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
        let previous = Entity::find()
            .filter(of_type(self.tag_type.as_deref()))
            .filter(Column::OrderColumn.lt(self.order_column))
            .order_by_desc(Column::OrderColumn)
            .order_by_desc(Column::Id)
            .one(db)
            .await?;
        match previous {
            Some(previous) => self.swap_order_with(db, &previous).await,
            None => Ok(()),
        }
    }

    /// Swaps positions with the next tag of the same type; nothing at the bottom.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn move_order_down<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
        let next = Entity::with_type(self.tag_type.as_deref())
            .filter(Column::OrderColumn.gt(self.order_column))
            .one(db)
            .await?;
        match next {
            Some(next) => self.swap_order_with(db, &next).await,
            None => Ok(()),
        }
    }

    /// Moves the tag to the first position of its type, shifting the ones before it.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn move_to_start<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
        let mut ids: Vec<i64> = self.siblings(db).await?;
        ids.retain(|id| *id != self.id);
        ids.insert(0, self.id);
        Entity::set_new_order(db, ids).await
    }

    /// Moves the tag to the last position of its type, shifting the ones after it.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn move_to_end<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
        let mut ids: Vec<i64> = self.siblings(db).await?;
        ids.retain(|id| *id != self.id);
        ids.push(self.id);
        Entity::set_new_order(db, ids).await
    }

    /// Swaps positions with `other`.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn swap_order_with<C: ConnectionTrait>(
        &self,
        db: &C,
        other: &Self,
    ) -> Result<(), DbErr> {
        for (id, position) in [(self.id, other.order_column), (other.id, self.order_column)] {
            Entity::update_many()
                .col_expr(Column::OrderColumn, Expr::value(position))
                .filter(Column::Id.eq(id))
                .exec(db)
                .await?;
        }
        Ok(())
    }

    /// The ids of the tags of this tag's type, by position.
    async fn siblings<C: ConnectionTrait>(&self, db: &C) -> Result<Vec<i64>, DbErr> {
        Entity::with_type(self.tag_type.as_deref())
            .select_only()
            .column(Column::Id)
            .into_tuple()
            .all(db)
            .await
    }

    /// The tag's key, for the pivot.
    pub(crate) const fn key(&self) -> Key {
        Key::Int(self.id)
    }
}

/// `text` with `%`, `_` and `\` escaped for a `LIKE ... ESCAPE '\'` pattern.
fn escape_like(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for character in text.chars() {
        if matches!(character, '%' | '_' | '\\') {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}