|
| 1 | +package com.sonkim.bookmarking.common.service; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 6 | +import org.springframework.stereotype.Service; |
| 7 | +import org.springframework.transaction.annotation.Transactional; |
| 8 | + |
| 9 | +@Service |
| 10 | +@RequiredArgsConstructor |
| 11 | +@Slf4j |
| 12 | +public class DatabaseCleanupService { |
| 13 | + |
| 14 | + private final JdbcTemplate jdbcTemplate; |
| 15 | + |
| 16 | + @Transactional |
| 17 | + public void runCleanup(String taskType) { |
| 18 | + log.info(">>>>> Scheduler Job Start: {}", taskType); |
| 19 | + int deletedCount; |
| 20 | + |
| 21 | + switch (taskType) { |
| 22 | + case "CLEANUP_UNUSED_TAGS" -> deletedCount = deleteUnusedTags(); |
| 23 | + case "CLEANUP_PENDING_TEAMS" -> deletedCount = deletePendingTeams(); |
| 24 | + case "CLEANUP_ORPHANED_TEAMS" -> deletedCount = deleteOrphanedTeams(); |
| 25 | + default -> throw new IllegalArgumentException("Invalid taskType: " + taskType); |
| 26 | + } |
| 27 | + |
| 28 | + log.info("TaskType: {} Completed, Deleted: {}", taskType, deletedCount); |
| 29 | + } |
| 30 | + |
| 31 | + private int deleteUnusedTags() { |
| 32 | + String sql = "DELETE t FROM tag t " + |
| 33 | + "LEFT JOIN bookmark_tag bt ON t.id = bt.tag_id " + |
| 34 | + "WHERE bt.tag_id IS NULL"; |
| 35 | + |
| 36 | + return jdbcTemplate.update(sql); |
| 37 | + } |
| 38 | + |
| 39 | + private int deletePendingTeams() { |
| 40 | + String sql = "DELETE FROM team " + |
| 41 | + "WHERE status = 'PENDING_DELETION' " + |
| 42 | + "AND deletion_scheduled_at < NOW()"; |
| 43 | + |
| 44 | + return jdbcTemplate.update(sql); |
| 45 | + } |
| 46 | + |
| 47 | + private int deleteOrphanedTeams() { |
| 48 | + String sql = "DELETE t FROM team t " + |
| 49 | + "WHERE NOT EXISTS (" + |
| 50 | + " SELECT 1 " + |
| 51 | + " FROM team_member tm " + |
| 52 | + " JOIN user u ON tm.account_id = u.id " + |
| 53 | + " WHERE tm.team_id = t.id " + |
| 54 | + " AND u.user_status = 'ACTIVE'" + |
| 55 | + ")"; |
| 56 | + |
| 57 | + return jdbcTemplate.update(sql); |
| 58 | + } |
| 59 | +} |
0 commit comments