sea-orm-sluggable 0.1.2

Unique, transliterated slugs for SeaORM entities
Documentation
use sea_orm::{ColumnTrait, Condition, ConnectionTrait, DbErr, EntityTrait, QueryFilter};

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

/// Builds a slug from `text` that no row of `E` has in `column` yet.
///
/// Returns the plain slug when it is free, otherwise adds a suffix:
/// `title`, `title-1`, `title-2`, ... (see [`SlugOptions`]).
/// To fill a model's slug column on save, use [`fill_slug`](crate::fill_slug).
///
/// # Errors
///
/// [`SlugError::Empty`] when `text` has no letters or digits, and
/// [`SlugError::Db`] when the database query fails.
pub async fn unique_slug<E, C>(
    db: &C,
    column: E::Column,
    text: &str,
    options: &SlugOptions,
) -> Result<String, SlugError>
where
    E: EntityTrait,
    C: ConnectionTrait,
{
    let base = slugify(text, options);
    pick_free::<E, C>(db, column, &base, options, Condition::all()).await
}

/// Finds the row of `E` whose `column` equals `slug`.
///
/// # Errors
///
/// When the database query fails.
pub async fn find_by_slug<E, C>(
    db: &C,
    column: E::Column,
    slug: &str,
) -> Result<Option<E::Model>, DbErr>
where
    E: EntityTrait,
    C: ConnectionTrait,
{
    E::find().filter(column.eq(slug)).one(db).await
}

/// First variant of `base` that is free among the rows matching `scope`.
pub async fn pick_free<E, C>(
    db: &C,
    column: E::Column,
    base: &str,
    options: &SlugOptions,
    scope: Condition,
) -> Result<String, SlugError>
where
    E: EntityTrait,
    C: ConnectionTrait,
{
    if base.is_empty() {
        return Err(SlugError::Empty);
    }
    if !options.always_suffix() && is_free::<E, C>(db, column, base, options, &scope).await? {
        return Ok(base.to_string());
    }

    let mut attempt = options.first_suffix();
    loop {
        let candidate = options.with_suffix(base, attempt);
        if is_free::<E, C>(db, column, &candidate, options, &scope).await? {
            return Ok(candidate);
        }
        attempt += 1;
    }
}

/// Neither reserved nor used by a row matching `scope`.
async fn is_free<E, C>(
    db: &C,
    column: E::Column,
    slug: &str,
    options: &SlugOptions,
    scope: &Condition,
) -> Result<bool, DbErr>
where
    E: EntityTrait,
    C: ConnectionTrait,
{
    if options.is_reserved(slug) {
        return Ok(false);
    }
    Ok(!is_taken::<E, C>(db, column, slug, scope.clone()).await?)
}

async fn is_taken<E, C>(
    db: &C,
    column: E::Column,
    slug: &str,
    scope: Condition,
) -> Result<bool, DbErr>
where
    E: EntityTrait,
    C: ConnectionTrait,
{
    let row = E::find()
        .filter(column.eq(slug))
        .filter(scope)
        .one(db)
        .await?;
    Ok(row.is_some())
}