use chrono::Utc;
use sea_orm::{
entity::prelude::*,
sea_query::{Expr, ExprTrait, Func},
ActiveValue::Set,
Condition, QueryOrder, QuerySelect,
};
use sea_orm_relations_kit::Key;
use sea_orm_sluggable::{SlugConfig, Sluggable};
use crate::{Taggable, TAGS};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "tags")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub name: String,
pub slug: String,
#[sea_orm(column_name = "type")]
pub tag_type: Option<String>,
pub order_column: i32,
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::taggable::Entity")]
Taggables,
}
impl Related<super::taggable::Entity> for Entity {
fn to() -> RelationDef {
Relation::Taggables.def()
}
}
impl Sluggable for ActiveModel {
fn slug_config() -> SlugConfig<Self> {
SlugConfig::new([Column::Name], Column::Slug)
.on_update(true)
.scope(|tag: &Self| of_type(tag.tag_type.try_as_ref().cloned().flatten().as_deref()))
}
}
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
let mut tag = sea_orm_sluggable::fill_slug(self, db, insert).await?;
let now = Utc::now().fixed_offset();
let tag_type = tag.tag_type.try_as_ref().cloned().flatten();
if insert {
tag.created_at = Set(now);
if tag.order_column.is_not_set() {
tag.order_column = Set(last_position(db, tag_type.as_deref()).await? + 1);
}
} else if tag.tag_type.is_set()
&& !tag.order_column.is_set()
&& moved_type(db, &tag, tag_type.as_deref()).await?
{
tag.order_column = Set(last_position(db, tag_type.as_deref()).await? + 1);
}
tag.updated_at = Set(now);
Ok(tag)
}
}
pub(crate) fn of_type(tag_type: Option<&str>) -> Condition {
let column = Column::TagType;
Condition::all().add(tag_type.map_or_else(|| column.is_null(), |tag_type| column.eq(tag_type)))
}
pub(crate) fn named(text: &str) -> Condition {
let text = text.trim();
Condition::any()
.add(Expr::expr(Func::lower(Expr::col(Column::Name))).eq(text.to_lowercase()))
.add(Column::Slug.eq(text))
}
async fn moved_type<C: ConnectionTrait>(
db: &C,
tag: &ActiveModel,
tag_type: Option<&str>,
) -> Result<bool, DbErr> {
let Some(id) = tag.id.try_as_ref() else {
return Ok(false);
};
let stored = Entity::find_by_id(*id).one(db).await?;
Ok(stored.is_some_and(|stored| stored.tag_type.as_deref() != tag_type))
}
async fn last_position<C: ConnectionTrait>(db: &C, tag_type: Option<&str>) -> Result<i32, DbErr> {
let last: Option<Option<i32>> = Entity::find()
.select_only()
.column_as(Expr::col(Column::OrderColumn).max(), "last")
.filter(of_type(tag_type))
.into_tuple()
.one(db)
.await?;
Ok(last.flatten().unwrap_or(0))
}
impl Entity {
pub async fn find_or_create<C, S>(
db: &C,
names: impl IntoIterator<Item = S> + Send,
tag_type: Option<&str>,
) -> Result<Vec<Model>, DbErr>
where
C: ConnectionTrait,
S: AsRef<str> + Send,
{
let mut tags = Vec::new();
for name in names {
let name = name.as_ref().trim();
let tag = match Self::find_from_string(db, name, tag_type).await? {
Some(tag) => tag,
None => {
ActiveModel {
name: Set(name.to_string()),
tag_type: Set(tag_type.map(str::to_string)),
..Default::default()
}
.insert(db)
.await?
}
};
if !tags.iter().any(|seen: &Model| seen.id == tag.id) {
tags.push(tag);
}
}
Ok(tags)
}
pub async fn find_from_string<C: ConnectionTrait>(
db: &C,
name: &str,
tag_type: Option<&str>,
) -> Result<Option<Model>, DbErr> {
Self::find()
.filter(named(name.trim()))
.filter(of_type(tag_type))
.order_by_asc(Column::Id)
.one(db)
.await
}
pub async fn find_many_from_string<C, S>(
db: &C,
names: impl IntoIterator<Item = S> + Send,
tag_type: Option<&str>,
) -> Result<Vec<Model>, DbErr>
where
C: ConnectionTrait,
S: AsRef<str> + Send,
{
let any_name = names.into_iter().fold(Condition::any(), |any, name| {
any.add(named(name.as_ref().trim()))
});
Self::with_type(tag_type).filter(any_name).all(db).await
}
pub async fn find_from_string_of_any_type<C: ConnectionTrait>(
db: &C,
name: &str,
) -> Result<Vec<Model>, DbErr> {
Self::ordered().filter(named(name.trim())).all(db).await
}
#[must_use]
pub fn ordered() -> Select<Self> {
Self::find()
.order_by_asc(Column::TagType)
.order_by_asc(Column::OrderColumn)
.order_by_asc(Column::Id)
}
#[must_use]
pub fn with_type(tag_type: Option<&str>) -> Select<Self> {
Self::ordered().filter(of_type(tag_type))
}
#[must_use]
pub fn containing(text: &str) -> Select<Self> {
let pattern = format!("%{}%", escape_like(&text.to_lowercase()));
Self::ordered().filter(
Expr::expr(Func::lower(Expr::col(Column::Name)))
.like(sea_orm::sea_query::LikeExpr::new(pattern).escape('\\')),
)
}
pub async fn types<C: ConnectionTrait>(db: &C) -> Result<Vec<String>, DbErr> {
Self::find()
.select_only()
.column(Column::TagType)
.filter(Column::TagType.is_not_null())
.distinct()
.order_by_asc(Column::TagType)
.into_tuple()
.all(db)
.await
}
pub async fn set_new_order<C: ConnectionTrait>(
db: &C,
ids: impl IntoIterator<Item = i64> + Send,
) -> Result<(), DbErr> {
for (position, id) in (1..).zip(ids) {
Self::update_many()
.col_expr(Column::OrderColumn, Expr::value(position))
.filter(Column::Id.eq(id))
.exec(db)
.await?;
}
Ok(())
}
}
impl Model {
pub fn tagged<O: Taggable>(&self) -> Result<Select<O>, DbErr> {
TAGS.owners_of::<O>(self)
}
pub async fn move_order_up<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
let previous = Entity::find()
.filter(of_type(self.tag_type.as_deref()))
.filter(Column::OrderColumn.lt(self.order_column))
.order_by_desc(Column::OrderColumn)
.order_by_desc(Column::Id)
.one(db)
.await?;
match previous {
Some(previous) => self.swap_order_with(db, &previous).await,
None => Ok(()),
}
}
pub async fn move_order_down<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
let next = Entity::with_type(self.tag_type.as_deref())
.filter(Column::OrderColumn.gt(self.order_column))
.one(db)
.await?;
match next {
Some(next) => self.swap_order_with(db, &next).await,
None => Ok(()),
}
}
pub async fn move_to_start<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
let mut ids: Vec<i64> = self.siblings(db).await?;
ids.retain(|id| *id != self.id);
ids.insert(0, self.id);
Entity::set_new_order(db, ids).await
}
pub async fn move_to_end<C: ConnectionTrait>(&self, db: &C) -> Result<(), DbErr> {
let mut ids: Vec<i64> = self.siblings(db).await?;
ids.retain(|id| *id != self.id);
ids.push(self.id);
Entity::set_new_order(db, ids).await
}
pub async fn swap_order_with<C: ConnectionTrait>(
&self,
db: &C,
other: &Self,
) -> Result<(), DbErr> {
for (id, position) in [(self.id, other.order_column), (other.id, self.order_column)] {
Entity::update_many()
.col_expr(Column::OrderColumn, Expr::value(position))
.filter(Column::Id.eq(id))
.exec(db)
.await?;
}
Ok(())
}
async fn siblings<C: ConnectionTrait>(&self, db: &C) -> Result<Vec<i64>, DbErr> {
Entity::with_type(self.tag_type.as_deref())
.select_only()
.column(Column::Id)
.into_tuple()
.all(db)
.await
}
pub(crate) const fn key(&self) -> Key {
Key::Int(self.id)
}
}
fn escape_like(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for character in text.chars() {
if matches!(character, '%' | '_' | '\\') {
escaped.push('\\');
}
escaped.push(character);
}
escaped
}