sea-orm-taggable 0.1.0

Tags for any SeaORM entity: attach, detach, sync, tag types, ordering and tag filters
Documentation

sea-orm-taggable

Tags for any SeaORM entity: attach, detach, sync, tag types, ordering and filters.

crates.io docs.rs CI license

One tags table serves posts, videos and anything else: post.tags().attach(db, ["Rust", "SeaORM"], None) creates the tags it needs, and posts::Entity::with_any_tags(["rust"], None) finds the posts. Think spatie/laravel-tags, for SeaORM.

Features

  • Any entity — one trait per entity; posts and videos with the same id keep their own tags
  • Tags from names — attaching a name creates the tag; names match ignoring case, or by slug
  • Slugs — made from the name with sea-orm-sluggable, unique within a tag type, any language transliterated
  • Types — group tags ("topic", "level"); plain tags are the None group
  • Order — each row keeps its tags in its own order; tags also have a position within their type
  • Filters — with any, all or none of the given tags, of one type or any type, untagged
  • Eager loading — the tags of a whole page in two queries
  • Tested — against SQLite and Postgres, every API doc example compiled

Built on sea-orm-relations-kit.

Installation

[dependencies]
sea-orm-taggable = "0.1"

The tables, in a migration:

use sea_orm_taggable::schema;

// up
manager.create_table(schema::tags_table()).await?;
manager.create_table(schema::taggables_table()).await?;
for index in schema::indexes() {
    manager.create_index(index).await?;
}

// down
for table in schema::drop_tables() {
    manager.drop_table(table).await?;
}

tags (id, name, slug, type, order_column, created_at, updated_at) and taggables (tag_id, taggable_type, taggable_id, position); deleting a tag removes it from every row.

Quick start

Mark the entity:

use sea_orm_taggable::{Morphable, Taggable};

impl Morphable for posts::Entity {
    const MORPH_TYPE: &'static str = "post";   // stored in taggables.taggable_type
}
impl Taggable for posts::Entity {}

Tag its rows:

use sea_orm_taggable::HasTags;

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
post.tags().detach(db, ["Loco"], None).await?;

let tags = post.tags().get(db).await?;                        // in the row's order
let levels = post.tags().of_type(db, Some("level")).await?;
let is_rust = post.tags().has(db, "rust", None).await?;

Find rows by their tags:

use sea_orm_taggable::TagFilters;

posts::Entity::find().filter(posts::Entity::with_any_tags(["rust", "go"], None));
posts::Entity::find().filter(posts::Entity::with_all_tags(["rust", "loco"], None));
posts::Entity::find().filter(posts::Entity::without_tags(["draft"], None));
posts::Entity::find().filter(posts::Entity::with_any_tags_of_type(["level"]));
posts::Entity::find().filter(posts::Entity::untagged());

A name with None matches plain tags only; with_any_tags_of_any_type and with_all_tags_of_any_type match every type.

The tags of a page of rows, in two queries:

let tags_per_post = sea_orm_taggable::load_tags(db, &posts).await?;
let counts = sea_orm_taggable::count_tags(db, &posts).await?;

Tags themselves

use sea_orm_taggable::tag;

let tags = tag::Entity::find_or_create(db, ["Rust", "Go"], None).await?;
let rust = tag::Entity::find_from_string(db, "rust", None).await?;      // by name or slug
let suggestions = tag::Entity::containing("ru").all(db).await?;          // ignoring case
let topics = tag::Entity::with_type(Some("topic")).all(db).await?;       // by position
let types = tag::Entity::types(db).await?;

rust.move_to_start(db).await?;      // also move_to_end, move_order_up / down, swap_order_with
tag::Entity::set_new_order(db, [go.id, rust.id]).await?;

let posts = rust.tagged::<posts::Entity>()?.all(db).await?;

Deleting tagged rows

The pivot cannot have a foreign key to the tagged rows. Detach in the row's delete hook:

post.tags().detach_all(db).await?;

or clean up from a scheduled task with sea_orm_taggable::delete_orphans::<posts::Entity, _>(db). With sea-orm-soft-delete, keep the tags in the trash and detach in after_force_delete.

Good to know

  • Tagged entities need integer primary keys (taggables.taggable_id is a BIGINT).
  • The partial unique indexes on slugs work on Postgres and SQLite, not MySQL.
  • Not in 0.1: translated tag names.

Coming from Laravel

spatie/laravel-tags sea-orm-taggable
use HasTags impl Taggable for posts::Entity {}
$post->attachTags(['a', 'b'], 'type') post.tags().attach(db, ["a", "b"], Some("type"))
$post->detachTag('a') post.tags().detach(db, ["a"], None)
$post->syncTags([...]) post.tags().sync(db, [...])
$post->syncTagsWithType([...], 'type') post.tags().sync_type(db, [...], Some("type"))
$post->tags / tagsWithType('type') post.tags().get(db) / of_type(db, Some("type"))
$post->hasTag('a') post.tags().has(db, "a", None)
Post::withAnyTags([...]) posts::Entity::with_any_tags([...], None)
withAllTags, withoutTags with_all_tags, without_tags
withAnyTagsOfAnyType, withAnyTagsOfType with_any_tags_of_any_type, with_any_tags_of_type
Tag::findOrCreate([...]) tag::Entity::find_or_create(db, [...], None)
Tag::findFromString('a') tag::Entity::find_from_string(db, "a", None)
Tag::containing('a') tag::Entity::containing("a")
Tag::getWithType('type'), getTypes() tag::Entity::with_type(Some("type")), types(db)
$tag->moveToStart() and friends tag.move_to_start(db) and friends

Contributing

Issues and pull requests are welcome. The tests run on in-memory SQLite; for Postgres set TAGGABLE_DATABASE_URL:

cargo test
TAGGABLE_DATABASE_URL=postgres://... cargo test --tests -- --test-threads=1

License

Licensed under either of Apache License, Version 2.0 or MIT license 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 · part of AxViLab