1- use crate :: model:: models:: { TagCondition , UpdateTagDTO } ;
1+ use crate :: model:: models:: { GroupTagCondition , TagCondition , UpdateTagDTO } ;
22use crate :: {
33 internal:: tags,
44 model:: models:: { CreateTagDTO , Tag , TagFilter } ,
55} ;
6- use diesel:: SqliteConnection ;
6+ use diesel:: { Connection , SqliteConnection } ;
77
88pub fn create_tag ( conn : & mut SqliteConnection , name : & str ) -> Result < Tag , diesel:: result:: Error > {
99 let new_tag = CreateTagDTO { name } ;
@@ -46,6 +46,30 @@ pub fn delete_tags_by_conditions(
4646 conn : & mut SqliteConnection ,
4747 conditions : Vec < TagCondition > ,
4848) -> Result < usize , diesel:: result:: Error > {
49- // TODO: 减少标签的引用计数
50- tags:: delete_tags_by_conditions ( conn, conditions)
51- }
49+ // 首先查询将要删除的标签
50+ let tags_to_delete = select_tags_by_conditions ( conn, conditions. clone ( ) , None )
51+ . map_err ( |e| match e {
52+ diesel:: result:: Error :: NotFound => diesel:: result:: Error :: NotFound ,
53+ _ => e,
54+ } ) ?;
55+
56+ // 使用事务确保数据一致性
57+ conn. transaction :: < _ , diesel:: result:: Error , _ > ( |conn| {
58+ let mut total_deleted = 0 ;
59+
60+ // 对于每个要删除的标签,处理相关的引用关系和关联数据
61+ for tag in & tags_to_delete {
62+ // 删除与该标签关联的所有组标签关系
63+ crate :: internal:: group_tag:: delete_group_tags_by_conditions (
64+ conn,
65+ vec ! [ GroupTagCondition :: TagId ( tag. id) ]
66+ ) ?;
67+
68+ // 删除标签本身
69+ let deleted_count = tags:: delete_tag ( conn, tag. id ) ?;
70+ total_deleted += deleted_count;
71+ }
72+
73+ Ok ( total_deleted)
74+ } )
75+ }
0 commit comments