sea-orm-sluggable 0.1.0

Unique, transliterated slugs for SeaORM entities
Documentation
<p align="center">
  <img src="https://raw.githubusercontent.com/axvilab/sea-orm-sluggable/main/assets/logo.png" alt="sea-orm-sluggable logo" width="128" height="128">
</p>

# sea-orm-sluggable

**Unique, readable URL slugs for [SeaORM](https://www.sea-ql.org/SeaORM/) entities, generated on save.**

[![crates.io](https://img.shields.io/crates/v/sea-orm-sluggable.svg)](https://crates.io/crates/sea-orm-sluggable)
[![docs.rs](https://img.shields.io/docsrs/sea-orm-sluggable)](https://docs.rs/sea-orm-sluggable)
[![CI](https://github.com/axvilab/sea-orm-sluggable/actions/workflows/ci.yml/badge.svg)](https://github.com/axvilab/sea-orm-sluggable/actions/workflows/ci.yml)
[![license](https://img.shields.io/crates/l/sea-orm-sluggable.svg)](#license)

Describe the slug once, and every insert gets one: `"Rust for PHP developers"` becomes
`rust-for-php-developers`, the next one `rust-for-php-developers-1`. Think
[spatie/laravel-sluggable](https://github.com/spatie/laravel-sluggable), for SeaORM.

## Features

- **Automatic** — one trait and one line in the save hook, no manual slug code
- **Unique** — `title`, `title-1`, `title-2`, …, optionally only within a scope (per category, per tenant)
- **Any language** — every script is transliterated to ASCII; official national rules per feature (`uk` today), or your own
- **Safe for URLs** — slugs stay stable on update by default; reserved words (`new`, `edit`) never become slugs
- **Flexible** — several source columns, separator, length, custom suffixes, conditional skipping
- **Tested** — against a real database (in-memory SQLite), every doc example compiled

## Installation

```toml
[dependencies]
sea-orm-sluggable = "0.1"
```

## Quick start

Describe the slug:

```rust
use sea_orm_sluggable::{SlugConfig, Sluggable};

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

Fill it in the save hook:

```rust
#[async_trait::async_trait]
impl ActiveModelBehavior for posts::ActiveModel {
    async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
        Ok(sea_orm_sluggable::fill_slug(self, db, insert).await?)
    }
}
```

That's it:

```rust
let post = posts::ActiveModel {
    title: Set("Hello, World!".to_string()),
    ..Default::default()
}
.insert(&db)
.await?;

assert_eq!(post.slug, "hello-world");

let found = sea_orm_sluggable::find_by_slug::<posts::Entity, _>(&db, posts::Column::Slug, "hello-world").await?;
```

## When the slug is generated

```rust
SlugConfig::new([posts::Column::Title], posts::Column::Slug)
    .on_create(true)          // default: on
    .on_update(true)          // default: off, see below
    .prevent_overwrite(true)  // default: off; keep a slug an editor typed in
    .skip_when(|post: &posts::ActiveModel| post.draft.clone().unwrap())
```

`on_update` is off by default: changing a slug breaks every link to the old URL. When it is
on, the slug is rebuilt only if a source column changed, and a row never collides with its
own slug.

### Several source columns

```rust
SlugConfig::new([people::Column::FirstName, people::Column::LastName], people::Column::Slug)
// "Ada", "Lovelace" -> "ada-lovelace"; empty and NULL columns are skipped
```

### Unique within a scope

```rust
SlugConfig::new([posts::Column::Title], posts::Column::Slug)
    .scope(|post: &posts::ActiveModel| {
        Condition::all().add(posts::Column::CategoryId.eq(post.category_id.clone().unwrap()))
    })
// "hello" can exist once per category
```

With [sea-orm-soft-delete](https://github.com/axvilab/sea-orm-soft-delete), scope to rows
outside the trash, so a trashed post frees its slug:

```rust
.scope(|_| Condition::all().add(posts::Column::DeletedAt.is_null()))
```

## Options

```rust
use sea_orm_sluggable::SlugOptions;

SlugConfig::new([posts::Column::Title], posts::Column::Slug).options(
    SlugOptions::default()
        .separator("_")                                      // default "-"
        .max_length(100)                                     // default 250, cut before the suffix
        .suffix_start(2)                                     // default 1: "title", "title-1", ...
        .suffix_on_first(true)                               // default off: "title-1" even when free
        .suffix_with(|_slug, attempt| format!("v{attempt}")) // "title-v1" instead of "title-1"
        .reserved(["new", "edit", "feed"]),                  // default none
)
```

### Reserved words

A post titled "New" must not take the slug `new` and shadow your `/posts/new` route. List the
words your routes use, and such a slug gets a suffix instead (`new-1`). The comparison ignores
case. The idea comes from Rails' [FriendlyId](https://github.com/norman/friendly_id).

### Without a model

```rust
let slug = sea_orm_sluggable::slugify("Hello, World!", &SlugOptions::default());
let slug = sea_orm_sluggable::unique_slug::<posts::Entity, _>(&db, posts::Column::Slug, "Hello", &options).await?;
```

## Languages

The default transliteration, `AnyAscii`, handles every script but knows no national rules.
For those, enable a language feature:

```toml
sea-orm-sluggable = { version = "0.1", features = ["uk"] }
```

```rust
use sea_orm_sluggable::{languages::Ukrainian, SlugOptions};

let options = SlugOptions::default().transliterator(Ukrainian);
// "Юрій Яковенко" -> "yurii-yakovenko"   (AnyAscii alone: "yuriy-yakovenko")
```

| Feature | Language | Rules |
|---|---|---|
| `uk` | Ukrainian | Cabinet of Ministers resolution No. 55 (2010) |

### Your own language

Implement `Transliterator` and pass it to `SlugOptions::transliterator`:

```rust
use sea_orm_sluggable::Transliterator;

struct Polish;

impl Transliterator for Polish {
    fn transliterate(&self, text: &str) -> String {
        // your table here
        text.to_string()
    }
}
```

### Adding a language to the package

1. Copy `src/languages/uk.rs` to `src/languages/<code>.rs` and replace the table.
2. Add tests built from the official examples of your national standard.
3. Add the feature to `Cargo.toml` and a `#[cfg(feature = "<code>")]` export in `src/languages/mod.rs`.
4. Add a row to the table above and open a pull request.

## Errors

`fill_slug` returns `SlugError::Empty` when the source has no letters or digits (for example
`"!!!"`), and `SlugError::Db` when the uniqueness query fails. Inside `before_save` the `?`
turns both into `DbErr`.

## Coming from Laravel

| spatie/laravel-sluggable (v6) | sea-orm-sluggable |
|---|---|
| `#[Sluggable]` / `use HasSlug` + `getSlugOptions()` | `impl Sluggable` + `fill_slug` in `before_save` |
| `from: 'title'` / `generateSlugsFrom('title')` | `SlugConfig::new([Column::Title], ...)` |
| `to: 'slug'` / `saveSlugsTo('slug')` | `SlugConfig::new(..., Column::Slug)` |
| `onUpdate: false` | the default; `.on_update(true)` to regenerate |
| `preventOverwrite: true` | `.prevent_overwrite(true)` |
| `skipGenerateWhen(fn)` | `.skip_when(fn)` |
| `extraScope(fn)` | `.scope(fn)` |
| `separator: '_'` | `SlugOptions::separator("_")` |
| `maxLength: 100` | `SlugOptions::max_length(100)` |
| `startSlugSuffixFrom(2)` | `SlugOptions::suffix_start(2)` |
| `useSuffixOnFirstOccurrence()` | `SlugOptions::suffix_on_first(true)` |
| `usingSuffixGenerator(fn)` | `SlugOptions::suffix_with(fn)` |
| `language: 'uk'` | `SlugOptions::transliterator(Ukrainian)` |
| `Post::findBySlug($slug)` | `find_by_slug::<posts::Entity, _>(...)` |
| — | `SlugOptions::reserved([...])` |

## Contributing

Issues and pull requests are welcome, language tables especially. The tests need no database
server:

```sh
cargo test --all-features
```

## License

Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT) at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion
in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above,
without any additional terms or conditions.

---

Made by [AxVi](https://axvi.dev) · part of [AxViLab](https://github.com/axvilab)