I'm moving this blog to Loco, which uses SeaORM for the database. Within the first week I needed four things SeaORM doesn't do on its own: slugs, soft deletes, polymorphic relations and tags.

So I wrote them as four small crates. Each does one job and depends only on SeaORM, so they work in Loco, plain axum or anything else that uses SeaORM. All four are on crates.io as 0.1. The tests run against a real database: SQLite for all four, Postgres too for relations-kit and taggable.

sea-orm-sluggable: unique slugs on save

Describe the slug once, and call it from SeaORM's save hook:

use sea_orm_sluggable::{SlugConfig, Sluggable}; impl Sluggable for posts::ActiveModel { fn slug_config() -> SlugConfig<Self> { SlugConfig::new([posts::Column::Title], posts::Column::Slug) } } #[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?) } } 

"Hello, World!" becomes hello-world, the next one hello-world-1. Slugs stay stable on update unless you ask otherwise (changing a slug breaks every link to the old URL). You can keep a slug an editor typed in, skip some rows, make slugs unique only within a scope (per category, per tenant), and change the separator, length or suffix format.

Two details I wanted for my own URLs:

  • Reserved words. A post titled "New" gets new-1 instead of shadowing a /posts/new route.
  • Transliteration. Every script becomes ASCII, and national rules can come in behind a feature: with uk, "Юрій" becomes yurii by the official Ukrainian standard.

The slug is checked, then saved, so two requests saving "Hello" at the same moment can both see hello as free. Back it with a unique index.

sea-orm-soft-delete: trash, restore, prune

Mark the entity, and its models get trash operations:

use sea_orm_soft_delete::{SoftDelete, SoftDeleteModel}; impl SoftDelete for posts::Entity { fn deleted_at_column() -> Self::Column { posts::Column::DeletedAt } } let post = post.soft_delete(&db).await?; // deleted_at = now let post = post.restore(&db).await?; post.force_delete(&db).await?; 

SeaORM has no global query scopes, so a plain posts::Entity::find() still returns trashed rows. You ask for live ones explicitly:

let live = posts::Entity::find_without_trashed().all(&db).await?; let trash = posts::Entity::find_only_trashed().all(&db).await?; let in_category = posts::Entity::find() .filter(posts::Column::CategoryId.eq(1)) .without_trashed() .all(&db) .await?; 

I keep every query for an entity in one repository module, so there's one place to get this right.

The rest: before/after hooks for each operation (a before_* hook can cancel it), *_quietly variants, bulk soft_delete_many / restore_many, and pruning of old trash, one row at a time with hooks or in one DELETE.

Two helpers guard the edges:

  • deny_hard_delete() in before_delete turns SeaORM's post.delete(db), which erases the row for good, into an error.
  • unique_while_kept(...) in a migration creates a partial unique index (WHERE deleted_at IS NULL), so a trashed hello doesn't block a new hello. A plain unique(slug, deleted_at) would let two live rows share a slug, because NULL never equals NULL.

sea-orm-relations-kit: polymorphic relations and pivots

SeaORM relations point at one table. Comments on posts and videos need a type column and an id column, and that's what this crate adds:

use sea_orm_relations_kit::{Morph, Morphable}; impl Morphable for posts::Entity { const MORPH_TYPE: &'static str = "post"; // a short alias, not a type name } pub const COMMENTABLE: Morph<comments::Entity> = Morph::new(comments::Column::CommentableType, comments::Column::CommentableId); let comments = COMMENTABLE.find_for(&post)?.all(db).await?; let per_post = COMMENTABLE.load_for(db, &posts).await?; // a whole page, one query let counts = COMMENTABLE.count_for(db, &posts).await?; // [3, 0, 1] 

From a comment back to its owner you get an enum, and a stored type the enum doesn't know is an error, not a silent None:

sea_orm_relations_kit::morph_target! { pub enum Commentable { Post(posts::Entity), Video(videos::Entity), } } let owner: Option<Commentable> = COMMENTABLE.owner(db, &comment).await?; 

For many-to-many, polymorphic or plain, there are the pivot operations: attach, detach, sync, sync_without_detaching, toggle, update_pivot, ordered pivots and extra pivot columns. For SeaORM's own Related relations it adds counts, sums and averages and "the latest row per owner". For polymorphic ones there are filters like "posts with at least one approved comment". Eager loading and counts work on a page of rows with one IN (...) query, or one per owner type, never one per row.

sea-orm-taggable: tags for any entity

One tags table for posts, videos and anything else:

use sea_orm_taggable::{HasTags, Morphable, TagFilters, Taggable}; impl Morphable for posts::Entity { const MORPH_TYPE: &'static str = "post"; } impl Taggable for posts::Entity {} post.tags().attach(db, ["Rust", "SeaORM"], None).await?; // creates missing tags post.tags().attach(db, ["Beginner"], Some("level")).await?; // a typed tag post.tags().sync(db, ["Rust", "Loco"]).await?; // exactly these, in this order posts::Entity::find().filter(posts::Entity::with_any_tags(["rust", "go"], None)); 

Tag types, ordering, find_or_create, containing("ru") for autocomplete and filters with any, all or none of the given tags are there, and migration helpers create both tables.

This is where the crates fit together: taggable uses relations-kit for the pivot and sluggable for tag slugs, unique within a tag type.

Getting them

[dependencies] sea-orm-sluggable = "0.1" sea-orm-soft-delete = "0.1" sea-orm-relations-kit = "0.1" sea-orm-taggable = "0.1" 
Crate What Code
sea-orm-sluggable unique slugs on save GitHub
sea-orm-soft-delete trash, restore, prune GitHub
sea-orm-relations-kit polymorphic relations, pivots, counts GitHub
sea-orm-taggable tags for any entity GitHub

Each README has the full API, and the packages page has all of them in one place.

Why 0.1

They're young. Every doc example in them compiles, but only one real app uses them so far: mine. If you try them in yours, I'd like to hear what's missing or awkward. Open an issue, or tell me what you still write by hand around SeaORM.

If you're building a web app with Loco, my book Loco for Laravel Developers walks through a whole blog, from loco new to a Docker deploy.

Originally published at axvi.dev.