sea-orm-taggable 0.1.1

Tags for any SeaORM entity: attach, detach, sync, tag types, ordering and tag filters
Documentation
//! Tags for any [SeaORM](https://www.sea-ql.org/SeaORM/) entity.
//!
//! One `tags` table serves every taggable entity through the polymorphic `taggables`
//! pivot. Mark an entity, and each of its rows gets a [`tags`](HasTags::tags) handle:
//!
//! ```no_run
//! # mod posts { use sea_orm::entity::prelude::*;
//! #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
//! #   #[sea_orm(table_name = "posts")]
//! #   pub struct Model { #[sea_orm(primary_key)] pub id: i32 }
//! #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
//! #   impl ActiveModelBehavior for ActiveModel {} }
//! use sea_orm::{DatabaseConnection, DbErr, EntityTrait, QueryFilter};
//! use sea_orm_taggable::{HasTags, Morphable, TagFilters, Taggable};
//!
//! impl Morphable for posts::Entity {
//!     const MORPH_TYPE: &'static str = "post";
//! }
//! impl Taggable for posts::Entity {}
//!
//! async fn example(db: &DatabaseConnection, post: &posts::Model) -> Result<(), DbErr> {
//!     post.tags().attach(db, ["Rust", "SeaORM"], None).await?;
//!     post.tags().attach(db, ["Beginner"], Some("level")).await?;
//!
//!     let about_rust = posts::Entity::find()
//!         .filter(posts::Entity::with_any_tags(["rust"], None))
//!         .all(db)
//!         .await?;
//!     Ok(())
//! }
//! ```
//!
//! - Tags are created from names on first use; a slug is made from the name, unique
//!   within the tag's type.
//! - **Types** group tags (`"topic"`, `"level"`); `None` is the plain group.
//! - Each row keeps its tags in its own order; tags also have a global position within
//!   their type ([`tag::Model::move_to_start`] and friends).
//! - Load the tags of a page of rows in two queries with [`load_tags`].
//!
//! The pivot cannot have a foreign key to the tagged rows, so call
//! [`Tags::detach_all`] in the row's delete hook (for soft-deleted rows, when they
//! are deleted for good), or [`delete_orphans`] from a scheduled task.

mod filter;
pub mod schema;
pub mod tag;
pub mod taggable;
mod tags;

use sea_orm::{ConnectionTrait, DbErr, ModelTrait};
use sea_orm_relations_kit::{Morph, MorphToMany};

pub use filter::TagFilters;
pub use sea_orm_relations_kit::{Changes, Key, Morphable};
pub use tags::{HasTags, TagInput, Tags};

/// An entity whose rows can be tagged. Its [`Morphable::MORPH_TYPE`] is stored in
/// `taggables.taggable_type`, and its primary key must be an integer.
pub trait Taggable: Morphable {}

/// The polymorphic many-to-many relation behind the tags, for queries this crate
/// does not cover; see `sea-orm-relations-kit`.
pub const TAGS: MorphToMany<taggable::Entity, tag::Entity> = MorphToMany::new(
    Morph::new(taggable::Column::TaggableType, taggable::Column::TaggableId),
    taggable::Column::TagId,
)
.ordered_by(taggable::Column::Position);

/// The tags of many rows, in two queries, each list in the row's own order.
///
/// # Errors
///
/// On a database error.
pub async fn load_tags<O, C>(db: &C, rows: &[O]) -> Result<Vec<Vec<tag::Model>>, DbErr>
where
    O: ModelTrait<Entity: Taggable> + Sync,
    C: ConnectionTrait,
{
    TAGS.load_for(db, rows).await
}

/// How many tags each row has, in one query.
///
/// # Errors
///
/// On a database error.
pub async fn count_tags<O, C>(db: &C, rows: &[O]) -> Result<Vec<u64>, DbErr>
where
    O: ModelTrait<Entity: Taggable> + Sync,
    C: ConnectionTrait,
{
    TAGS.count_for(db, rows).await
}

/// Removes the pivot rows of `O` rows that no longer exist. Returns how many went.
///
/// # Errors
///
/// On a database error.
pub async fn delete_orphans<O, C>(db: &C) -> Result<u64, DbErr>
where
    O: Taggable,
    C: ConnectionTrait,
{
    TAGS.delete_orphans::<O, C>(db).await
}