sea-orm-sluggable 0.1.1

Unique, transliterated slugs for SeaORM entities
Documentation
//! Runs against an in-memory SQLite database, so the package needs no server to test.

use sea_orm::{
    entity::prelude::*,
    ActiveValue::{Set, Unchanged},
    Condition, Database, DatabaseConnection, Schema,
};
use sea_orm_sluggable::{
    fill_slug, fill_slug_with, find_by_slug, unique_slug, SlugConfig, SlugError, SlugOptions,
    Sluggable,
};

#[allow(clippy::empty_enums)] // the test table has no relations
mod article {
    use sea_orm::entity::prelude::*;

    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "articles")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub title: String,
        pub subtitle: Option<String>,
        pub slug: String,
        pub group_id: i32,
        pub draft: bool,
    }

    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
}

/// The way an app uses the package: the slug is filled in by the save hook.
#[async_trait::async_trait]
impl ActiveModelBehavior for article::ActiveModel {
    async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
        Ok(fill_slug(self, db, insert).await?)
    }
}

impl Sluggable for article::ActiveModel {
    fn slug_config() -> SlugConfig<Self> {
        SlugConfig::new([article::Column::Title], article::Column::Slug)
    }
}

async fn db() -> DatabaseConnection {
    let db = Database::connect("sqlite::memory:").await.unwrap();
    let table = Schema::new(db.get_database_backend()).create_table_from_entity(article::Entity);
    db.execute(&table).await.unwrap();
    db
}

fn draft(title: &str) -> article::ActiveModel {
    article::ActiveModel {
        title: Set(title.to_string()),
        subtitle: Set(None),
        group_id: Set(1),
        draft: Set(false),
        ..Default::default()
    }
}

async fn insert(db: &DatabaseConnection, title: &str) -> article::Model {
    draft(title).insert(db).await.unwrap()
}

/// Fills the slug with an explicit `config`, then inserts through `Entity::insert`,
/// which skips the `before_save` hook, so only `config` decides the slug.
async fn insert_with(
    db: &DatabaseConnection,
    model: article::ActiveModel,
    config: &SlugConfig<article::ActiveModel>,
) -> Result<article::Model, SlugError> {
    let model = fill_slug_with(model, db, true, config).await?;
    Ok(article::Entity::insert(model)
        .exec_with_returning(db)
        .await?)
}

#[tokio::test]
async fn generates_the_slug_on_insert() {
    let db = db().await;
    assert_eq!(
        insert(&db, "Rust for PHP developers").await.slug,
        "rust-for-php-developers"
    );
}

#[tokio::test]
async fn numbers_taken_slugs() {
    let db = db().await;
    let slugs = [
        insert(&db, "Hello").await.slug,
        insert(&db, "Hello").await.slug,
        insert(&db, "Hello!").await.slug,
    ];
    assert_eq!(slugs, ["hello", "hello-1", "hello-2"]);
}

#[tokio::test]
async fn keeps_the_slug_on_update_by_default() {
    let db = db().await;
    let mut article: article::ActiveModel = insert(&db, "Old title").await.into();
    article.title = Set("New title".to_string());

    assert_eq!(article.update(&db).await.unwrap().slug, "old-title");
}

#[tokio::test]
async fn regenerates_on_update_without_colliding_with_itself() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug).on_update(true);
    let saved = insert(&db, "Hello").await;

    let mut article: article::ActiveModel = saved.into();
    article.title = Set("Hello".to_string());
    let article = fill_slug_with(article, &db, false, &config).await.unwrap();

    assert_eq!(article.slug.unwrap(), "hello");
}

#[tokio::test]
async fn regenerates_on_update_only_when_a_source_changed() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug).on_update(true);
    let saved = insert(&db, "Hello").await;

    let mut article: article::ActiveModel = saved.into();
    article.slug = Set("hand-made".to_string());
    let article = fill_slug_with(article, &db, false, &config).await.unwrap();

    assert_eq!(article.slug.unwrap(), "hand-made");
}

#[tokio::test]
async fn prevent_overwrite_keeps_a_typed_slug() {
    let db = db().await;
    let config =
        SlugConfig::new([article::Column::Title], article::Column::Slug).prevent_overwrite(true);
    let mut model = draft("Hello");
    model.slug = Set("my-own".to_string());

    let saved = insert_with(&db, model, &config).await.unwrap();

    assert_eq!(saved.slug, "my-own");
}

#[tokio::test]
async fn builds_from_several_columns_and_skips_empty_ones() {
    let db = db().await;
    let config = SlugConfig::new(
        [article::Column::Title, article::Column::Subtitle],
        article::Column::Slug,
    );
    let mut with_subtitle = draft("Rust");
    with_subtitle.subtitle = Set(Some("Part 2".to_string()));

    let first = insert_with(&db, with_subtitle, &config).await.unwrap();
    let second = insert_with(&db, draft("Go"), &config).await.unwrap();

    assert_eq!([first.slug, second.slug], ["rust-part-2", "go"]);
}

#[tokio::test]
async fn scope_allows_the_same_slug_in_another_group() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug).scope(
        |article: &article::ActiveModel| {
            Condition::all().add(article::Column::GroupId.eq(article.group_id.clone().unwrap()))
        },
    );
    let mut other_group = draft("Hello");
    other_group.group_id = Set(2);

    let first = insert_with(&db, draft("Hello"), &config).await.unwrap();
    let same_group = insert_with(&db, draft("Hello"), &config).await.unwrap();
    let other = insert_with(&db, other_group, &config).await.unwrap();

    assert_eq!(
        [first.slug, same_group.slug, other.slug],
        ["hello", "hello-1", "hello"]
    );
}

#[tokio::test]
async fn skip_when_leaves_the_slug_alone() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug)
        .skip_when(|article: &article::ActiveModel| article.draft.clone().unwrap());
    let mut model = draft("Hello");
    model.draft = Set(true);

    let model = fill_slug_with(model, &db, true, &config).await.unwrap();

    assert!(model.slug.is_not_set());
}

#[tokio::test]
async fn custom_suffixes() {
    let db = db().await;
    let options = SlugOptions::default()
        .suffix_start(2)
        .suffix_on_first(true)
        .suffix_with(|_, attempt| format!("v{attempt}"));

    let first = unique_slug::<article::Entity, _>(&db, article::Column::Slug, "Hello", &options)
        .await
        .unwrap();
    insert(&db, "Hello").await;
    let mut taken = draft("x");
    taken.slug = Set("hello-v2".to_string());
    article::Entity::insert(taken).exec(&db).await.unwrap();
    let second = unique_slug::<article::Entity, _>(&db, article::Column::Slug, "Hello", &options)
        .await
        .unwrap();

    assert_eq!([first, second], ["hello-v2", "hello-v3"]);
}

#[tokio::test]
async fn refuses_text_without_letters() {
    let db = db().await;
    let error = draft("!!!").insert(&db).await.unwrap_err();
    assert!(error.to_string().contains("empty slug"), "{error}");
}

#[tokio::test]
async fn finds_rows_by_slug() {
    let db = db().await;
    insert(&db, "Hello").await;

    let found = find_by_slug::<article::Entity, _>(&db, article::Column::Slug, "hello")
        .await
        .unwrap();
    let missing = find_by_slug::<article::Entity, _>(&db, article::Column::Slug, "nope")
        .await
        .unwrap();

    assert_eq!(found.map(|a| a.title), Some("Hello".to_string()));
    assert!(missing.is_none());
}

#[tokio::test]
async fn reserved_words_are_never_used_as_slugs() {
    let db = db().await;
    let options = SlugOptions::default().reserved(["new", "Edit"]);

    let mut slugs = Vec::new();
    for title in ["New", "edit", "News"] {
        slugs.push(
            unique_slug::<article::Entity, _>(&db, article::Column::Slug, title, &options)
                .await
                .unwrap(),
        );
    }

    assert_eq!(slugs, ["new-1", "edit-1", "news"]);
}

#[tokio::test]
async fn reserved_words_apply_on_save() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug)
        .options(SlugOptions::default().reserved(["feed"]));

    let saved = insert_with(&db, draft("Feed"), &config).await.unwrap();

    assert_eq!(saved.slug, "feed-1");
}

// ---- Regressions found in review ------------------------------------------------------

#[tokio::test]
async fn saving_the_same_title_again_keeps_a_suffixed_slug() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug).on_update(true);
    let first = insert(&db, "Hello").await;
    let second = insert(&db, "Hello").await;
    assert_eq!(second.slug, "hello-1");
    article::Entity::delete_by_id(first.id)
        .exec(&db)
        .await
        .unwrap();

    let mut article: article::ActiveModel = second.into();
    article.title = Set("Hello".to_string());
    let article = fill_slug_with(article, &db, false, &config).await.unwrap();

    assert_eq!(article.slug.unwrap(), "hello-1");
}

#[tokio::test]
async fn a_new_title_still_gets_a_new_slug_on_update() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug).on_update(true);
    let saved = insert(&db, "Hello").await;

    let mut article: article::ActiveModel = saved.into();
    article.title = Set("Hello World".to_string());
    let article = fill_slug_with(article, &db, false, &config).await.unwrap();

    assert_eq!(article.slug.unwrap(), "hello-world");
}

#[tokio::test]
async fn a_partial_update_with_some_sources_unset_keeps_the_slug() {
    let db = db().await;
    let config = SlugConfig::new(
        [article::Column::Title, article::Column::Subtitle],
        article::Column::Slug,
    )
    .on_update(true);
    let saved = insert(&db, "Ada").await;

    let partial = article::ActiveModel {
        id: Unchanged(saved.id),
        subtitle: Set(Some("Lovelace".to_string())),
        ..Default::default()
    };
    let partial = fill_slug_with(partial, &db, false, &config).await.unwrap();

    assert!(partial.slug.is_not_set());
}

#[tokio::test]
async fn a_suffixed_slug_fits_max_length() {
    let db = db().await;
    let config = SlugConfig::new([article::Column::Title], article::Column::Slug)
        .options(SlugOptions::default().max_length(8));
    insert_with(&db, draft("Abcdefghij"), &config)
        .await
        .unwrap();

    let second = insert_with(&db, draft("Abcdefghij"), &config)
        .await
        .unwrap();

    assert_eq!(second.slug, "abcdef-1");
}