sea-orm-sluggable 0.1.0

Unique, transliterated slugs for SeaORM entities
Documentation
use sea_orm::{
    sea_query::ValueType, ActiveModelTrait, ActiveValue, ColumnTrait, Condition, ConnectionTrait,
    EntityTrait, Iterable, PrimaryKeyToColumn, Value,
};

use crate::{config::SlugOptions, db::pick_free, error::SlugError, text::slugify};

type Column<A> = <<A as ActiveModelTrait>::Entity as EntityTrait>::Column;
type Predicate<A> = Box<dyn Fn(&A) -> bool + Send + Sync>;
type ScopeFn<A> = Box<dyn Fn(&A) -> Condition + Send + Sync>;

/// Gives an `ActiveModel` an automatically generated slug.
///
/// ```
/// # mod categories {
/// #     use sea_orm::entity::prelude::*;
/// #     #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
/// #     #[sea_orm(table_name = "categories")]
/// #     pub struct Model {
/// #         #[sea_orm(primary_key)]
/// #         pub id: i32,
/// #         pub title: String,
/// #         pub slug: String,
/// #     }
/// #     #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
/// #     pub enum Relation {}
/// # }
/// use sea_orm::entity::prelude::*;
/// use sea_orm_sluggable::{SlugConfig, Sluggable};
///
/// impl Sluggable for categories::ActiveModel {
///     fn slug_config() -> SlugConfig<Self> {
///         SlugConfig::new([categories::Column::Title], categories::Column::Slug)
///     }
/// }
///
/// #[async_trait::async_trait]
/// impl ActiveModelBehavior for categories::ActiveModel {
///     async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
///         // "Rust for PHP developers" -> "rust-for-php-developers",
///         // or "rust-for-php-developers-1" when that one is taken.
///         Ok(sea_orm_sluggable::fill_slug(self, db, insert).await?)
///     }
/// }
/// # fn main() {}
/// ```
pub trait Sluggable: ActiveModelTrait + Send {
    /// Where the slug comes from, where it goes, and how it is built.
    fn slug_config() -> SlugConfig<Self>;
}

/// Which columns a slug is built from and stored in, and when it is generated.
pub struct SlugConfig<A: ActiveModelTrait> {
    sources: Vec<Column<A>>,
    target: Column<A>,
    options: SlugOptions,
    on_create: bool,
    on_update: bool,
    prevent_overwrite: bool,
    skip_when: Option<Predicate<A>>,
    scope: Option<ScopeFn<A>>,
}

impl<A: ActiveModelTrait> SlugConfig<A> {
    /// Builds the slug from `sources` (joined with a space, in order) into `target`.
    ///
    /// Defaults: generated on create, kept on update, unique across the whole table.
    pub fn new(sources: impl IntoIterator<Item = Column<A>>, target: Column<A>) -> Self {
        Self {
            sources: sources.into_iter().collect(),
            target,
            options: SlugOptions::default(),
            on_create: true,
            on_update: false,
            prevent_overwrite: false,
            skip_when: None,
            scope: None,
        }
    }

    /// Separator, length, suffixes and transliteration.
    #[must_use]
    pub fn options(mut self, options: SlugOptions) -> Self {
        self.options = options;
        self
    }

    /// Generate the slug when a row is inserted. Default: on.
    #[must_use]
    pub const fn on_create(mut self, enabled: bool) -> Self {
        self.on_create = enabled;
        self
    }

    /// Regenerate the slug when a source column changes on update. Default: off,
    /// because changing a slug breaks every link to the old URL.
    #[must_use]
    pub const fn on_update(mut self, enabled: bool) -> Self {
        self.on_update = enabled;
        self
    }

    /// Keep a slug that is already filled in, for example typed by an editor.
    /// Default: off.
    #[must_use]
    pub const fn prevent_overwrite(mut self, enabled: bool) -> Self {
        self.prevent_overwrite = enabled;
        self
    }

    /// Leave the slug alone when `skip` returns `true`, e.g. for drafts.
    #[must_use]
    pub fn skip_when(mut self, skip: impl Fn(&A) -> bool + Send + Sync + 'static) -> Self {
        self.skip_when = Some(Box::new(skip));
        self
    }

    /// Makes the slug unique only among rows matching the returned condition,
    /// e.g. within one category or tenant.
    ///
    /// ```
    /// # 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,
    /// #         pub category_id: i32,
    /// #         pub title: String,
    /// #         pub slug: String,
    /// #     }
    /// #     #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    /// #     pub enum Relation {}
    /// #     impl ActiveModelBehavior for ActiveModel {}
    /// # }
    /// use sea_orm::{entity::prelude::*, Condition};
    /// use sea_orm_sluggable::SlugConfig;
    ///
    /// // "hello" can exist once per category.
    /// let config = SlugConfig::new([posts::Column::Title], posts::Column::Slug).scope(
    ///     |post: &posts::ActiveModel| {
    ///         Condition::all().add(posts::Column::CategoryId.eq(post.category_id.clone().unwrap()))
    ///     },
    /// );
    /// ```
    #[must_use]
    pub fn scope(mut self, scope: impl Fn(&A) -> Condition + Send + Sync + 'static) -> Self {
        self.scope = Some(Box::new(scope));
        self
    }
}

/// Fills the slug column of `model` using [`Sluggable::slug_config`].
///
/// Call it from `ActiveModelBehavior::before_save`; `insert` is the flag that
/// hook receives.
///
/// # Errors
///
/// [`SlugError::Empty`] when the source columns give no letters or digits,
/// and [`SlugError::Db`] when the uniqueness check fails.
pub async fn fill_slug<A, C>(model: A, db: &C, insert: bool) -> Result<A, SlugError>
where
    A: Sluggable,
    C: ConnectionTrait,
{
    let config = A::slug_config();
    fill_slug_with(model, db, insert, &config).await
}

/// Same as [`fill_slug`], with an explicit configuration.
///
/// # Errors
///
/// [`SlugError::Empty`] when the source columns give no letters or digits,
/// and [`SlugError::Db`] when the uniqueness check fails.
pub async fn fill_slug_with<A, C>(
    mut model: A,
    db: &C,
    insert: bool,
    config: &SlugConfig<A>,
) -> Result<A, SlugError>
where
    A: ActiveModelTrait + Send,
    C: ConnectionTrait,
{
    if !should_generate(&model, insert, config) {
        return Ok(model);
    }

    let base = slugify(&source_text(&model, &config.sources), &config.options);
    let mut scope = config
        .scope
        .as_ref()
        .map_or_else(Condition::all, |scope| scope(&model));
    if !insert {
        if let Some(itself) = primary_key_condition(&model) {
            scope = scope.add(itself.not());
        }
    }

    let slug = pick_free::<A::Entity, C>(db, config.target, &base, &config.options, scope).await?;
    model.set(config.target, slug.into());
    Ok(model)
}

fn should_generate<A: ActiveModelTrait>(model: &A, insert: bool, config: &SlugConfig<A>) -> bool {
    let enabled = if insert {
        config.on_create
    } else {
        config.on_update
            && config
                .sources
                .iter()
                .any(|column| model.get(*column).is_set())
    };
    if !enabled {
        return false;
    }
    if config.skip_when.as_ref().is_some_and(|skip| skip(model)) {
        return false;
    }
    !(config.prevent_overwrite && text_of(model.get(config.target)).is_some_and(|s| !s.is_empty()))
}

/// The source columns joined with spaces; empty and non-text columns are skipped.
fn source_text<A: ActiveModelTrait>(model: &A, sources: &[Column<A>]) -> String {
    sources
        .iter()
        .filter_map(|column| text_of(model.get(*column)))
        .collect::<Vec<_>>()
        .join(" ")
}

fn text_of(value: ActiveValue<Value>) -> Option<String> {
    let value = value.into_value()?;
    <Option<String> as ValueType>::try_from(value)
        .ok()
        .flatten()
}

/// `WHERE pk = <this row's pk>`, or `None` when the primary key is not loaded.
fn primary_key_condition<A: ActiveModelTrait>(model: &A) -> Option<Condition> {
    let mut condition = Condition::all();
    for key in <<A::Entity as EntityTrait>::PrimaryKey as Iterable>::iter() {
        let column = key.into_column();
        let value = model.get(column).into_value()?;
        condition = condition.add(column.eq(value));
    }
    Some(condition)
}