Repository navigation
[BUG] 챌린지 수정 시 요일 중복 에러 해결 #378
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
4051091
feat: 챌린지 수정 메소드 추가
Hminkyung 2594e63
feat: distinct 방어 코드 적용
Hminkyung a5b6aa3
feat: 챌린지 수정 변경한거 반영
Hminkyung e82cb90
feat: 챌린지 중복 요일 제거 migration 쿼리 추가
Hminkyung f2e72d9
feat: 테스트 코드 추가
Hminkyung f2ab4f0
feat: 테스트 코드에 누락된 어노테이션 추가
Hminkyung 532a0bd
feat: 코드리뷰 반영
Hminkyung File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
src/main/resources/db/migration/V2.48__clean_duplicated_challenge_day_join.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| -- 챌린지 인증 요일(challenge_day_join) 중복 데이터 정리 | ||
| -- | ||
| -- [배경] | ||
| -- 챌린지 수정(updateChallenge) 시 기존 요일을 Repository로 직접 삭제한 뒤 새 요일을 저장했으나, | ||
| -- Challenge.challengeDays에 cascade = ALL(PERSIST 포함)이 걸려 있고 | ||
| -- 영속성 컨텍스트의 컬렉션에 기존 엔티티가 그대로 남아 있어 flush 시점에 예약된 DELETE가 취소됨. | ||
| -- 그 결과 기존 요일이 남은 채 새 요일이 INSERT 되어 요일이 중복 누적됨. (예: 월,월,수,수,금,금) | ||
| -- | ||
| -- [정리 기준] | ||
| -- 단순 중복 제거만 하면 "월수금 -> 화목"처럼 요일 구성을 바꾼 수정이 반영되지 않는다. | ||
| -- 따라서 챌린지별로 "마지막으로 저장된 요일 세트"만 남겨야 한다. | ||
| -- | ||
| -- 1단계 : 챌린지별로 마지막 저장 배치의 시작 지점을 찾아, 그 이전에 저장된 행을 삭제 | ||
| -- 한 번의 저장(saveAll)은 밀리초 단위로 끝나고 서로 다른 저장은 최소 수 분~수 일 차이가 나므로, | ||
| -- 연속된 저장 시각 사이의 간격이 BATCH_GAP(5초)을 넘는 지점을 배치 경계로 판단한다. | ||
| -- (최신 시각에서 고정 시간을 빼는 방식은 저장이 오래 걸리면 정상 행을 지울 수 있어 사용하지 않음) | ||
| -- 2단계 : 남은 행에서 (challenge_id, day_of_week) 중복 제거 (가장 작은 id만 유지) | ||
| -- 생성 시점에 프론트가 중복 요일을 보낸 경우를 대비한 방어 단계 | ||
| -- | ||
| -- [안전 장치] | ||
| -- - 저장 배치가 하나뿐인 챌린지는 배치 경계가 존재하지 않으므로 1단계 삭제 대상에서 완전히 제외된다. | ||
| -- - 각 챌린지는 최소 1개 이상의 요일 행이 반드시 남는다. | ||
| -- (1단계는 마지막 배치를 항상 보존하고, 2단계는 그룹당 MIN(id)를 보존) | ||
| -- | ||
| -- [배포 전 사전 검증 쿼리] | ||
| -- 삭제 예정 행 수 확인 (아래 1단계 DELETE를 SELECT로 바꿔서 실행) | ||
| -- SELECT COUNT(*) FROM challenge_day_join; -- 정리 전 총 행 수 기록 | ||
| -- | ||
| -- [배포 후 사후 검증 쿼리] | ||
| -- -- (1) 중복이 남아 있으면 안 됨. 결과 0건이어야 정상 | ||
| -- SELECT challenge_id, day_of_week, COUNT(*) | ||
| -- FROM challenge_day_join GROUP BY challenge_id, day_of_week HAVING COUNT(*) > 1; | ||
| -- | ||
| -- -- (2) 요일이 0개가 된 챌린지가 있으면 안 됨. 결과 0건이어야 정상 | ||
| -- SELECT c.id FROM challenge c | ||
| -- LEFT JOIN challenge_day_join cdj ON cdj.challenge_id = c.id | ||
| -- WHERE cdj.id IS NULL; | ||
|
|
||
| -- 1단계) 챌린지별 마지막 저장 배치의 시작 시각 이전에 저장된 요일 행 삭제 | ||
| DELETE cdj | ||
| FROM challenge_day_join cdj | ||
| JOIN ( | ||
| -- 간격이 5초를 초과하는 지점 중 가장 마지막 = 마지막 저장 배치의 시작 시각 | ||
| SELECT challenge_id, MAX(created_at) AS last_batch_started_at | ||
| FROM ( | ||
| SELECT challenge_id, | ||
| created_at, | ||
| TIMESTAMPDIFF( | ||
| MICROSECOND, | ||
| LAG(created_at) OVER (PARTITION BY challenge_id ORDER BY created_at), | ||
| created_at | ||
| ) AS gap_microseconds | ||
| FROM (SELECT DISTINCT challenge_id, created_at FROM challenge_day_join) distinct_saved_at | ||
| ) gaps | ||
| WHERE gap_microseconds > 5000000 -- BATCH_GAP: 5초 | ||
| GROUP BY challenge_id | ||
| ) last_batch ON last_batch.challenge_id = cdj.challenge_id | ||
| WHERE cdj.created_at < last_batch.last_batch_started_at; | ||
|
|
||
| -- 2단계) 남은 행에서 (challenge_id, day_of_week) 중복 제거 | ||
| DELETE cdj | ||
| FROM challenge_day_join cdj | ||
| JOIN ( | ||
| SELECT challenge_id, day_of_week, MIN(id) AS keep_id | ||
| FROM challenge_day_join | ||
| GROUP BY challenge_id, day_of_week | ||
| ) keeper ON keeper.challenge_id = cdj.challenge_id | ||
| AND keeper.day_of_week = cdj.day_of_week | ||
| WHERE cdj.id > keeper.keep_id; |
181 changes: 181 additions & 0 deletions
181
src/test/java/com/hrr/backend/domain/challenge/repository/ChallengeDayJoinReplaceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| package com.hrr.backend.domain.challenge.repository; | ||
|
|
||
| import com.hrr.backend.domain.challenge.entity.Challenge; | ||
| import com.hrr.backend.domain.challenge.entity.ChallengeDayJoin; | ||
| import com.hrr.backend.global.common.enums.Category; | ||
| import com.hrr.backend.global.common.enums.ChallengeDays; | ||
| import com.hrr.backend.global.common.enums.ChallengeStatus; | ||
| import com.hrr.backend.global.common.enums.VerificationType; | ||
| import com.querydsl.jpa.impl.JPAQueryFactory; | ||
| import jakarta.persistence.EntityManager; | ||
| import jakarta.persistence.PersistenceContext; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; | ||
| import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; | ||
| import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; | ||
| import org.springframework.boot.test.context.TestConfiguration; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.test.context.ActiveProfiles; | ||
| import java.time.LocalDateTime; | ||
| import java.time.LocalTime; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| /** | ||
| * 챌린지 인증 요일 교체(Challenge.updateChallengeDays) 검증 테스트 | ||
| */ | ||
| @DataJpaTest | ||
| @ActiveProfiles("test") | ||
| @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) | ||
| @DisplayName("챌린지 인증 요일 교체 - Challenge.updateChallengeDays()") | ||
| class ChallengeDayJoinReplaceTest { | ||
|
|
||
| @Autowired | ||
| private ChallengeRepository challengeRepository; | ||
|
|
||
| @Autowired | ||
| private ChallengeDayJoinRepository challengeDayJoinRepository; | ||
|
|
||
| @Autowired | ||
| private TestEntityManager entityManager; | ||
|
|
||
| @TestConfiguration | ||
| static class QueryDslTestConfig { | ||
| @PersistenceContext | ||
| private EntityManager entityManager; | ||
|
|
||
| @Bean | ||
| public JPAQueryFactory jpaQueryFactory() { | ||
| return new JPAQueryFactory(entityManager); | ||
| } | ||
| } | ||
|
|
||
| private Long challengeId; | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| // Given: 월/수/금으로 챌린지 생성 | ||
| Challenge challenge = createChallenge(); | ||
| addDays(challenge, ChallengeDays.MONDAY, ChallengeDays.WEDNESDAY, ChallengeDays.FRIDAY); | ||
|
|
||
| challengeRepository.save(challenge); | ||
| flushAndClear(); | ||
|
|
||
| challengeId = challenge.getId(); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("요일 구성을 바꿔서 수정하면 기존 요일은 모두 삭제되고 새 요일만 남아야 한다") | ||
| void updateChallengeDays_replacesAllDays() { | ||
| // When: 월/수/금 -> 화/목 으로 교체 | ||
| Challenge challenge = findWithDays(); | ||
| challenge.updateChallengeDays(List.of(ChallengeDays.TUESDAY, ChallengeDays.THURSDAY)); | ||
| flushAndClear(); | ||
|
|
||
| // Then | ||
| assertThat(findDays()).containsExactlyInAnyOrder(ChallengeDays.TUESDAY, ChallengeDays.THURSDAY); | ||
| assertThat(countAllRows()).isEqualTo(2); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("[회귀] 동일한 요일로 다시 저장해도 요일이 중복 누적되지 않아야 한다") | ||
| void updateChallengeDays_withSameDays_doesNotDuplicate() { | ||
| // When: 월/수/금 -> 월/수/금 (요일은 그대로 두고 다른 항목만 수정한 상황) | ||
| Challenge challenge = findWithDays(); | ||
| challenge.updateChallengeDays(List.of(ChallengeDays.MONDAY, ChallengeDays.WEDNESDAY, ChallengeDays.FRIDAY)); | ||
| flushAndClear(); | ||
|
|
||
| // Then: 월,월,수,수,금,금 (6건)이 아니라 월,수,금 (3건)이어야 한다 | ||
| assertThat(findDays()).containsExactlyInAnyOrder( | ||
| ChallengeDays.MONDAY, ChallengeDays.WEDNESDAY, ChallengeDays.FRIDAY); | ||
| assertThat(countAllRows()).isEqualTo(3); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("[회귀] 여러 번 수정해도 요일이 누적되지 않고 마지막 수정 값만 남아야 한다") | ||
| void updateChallengeDays_multipleTimes_doesNotAccumulate() { | ||
| // When: 1차 수정 | ||
| findWithDays().updateChallengeDays(List.of(ChallengeDays.MONDAY, ChallengeDays.WEDNESDAY, ChallengeDays.FRIDAY)); | ||
| flushAndClear(); | ||
|
|
||
| // When: 2차 수정 | ||
| findWithDays().updateChallengeDays(List.of(ChallengeDays.TUESDAY)); | ||
| flushAndClear(); | ||
|
|
||
| // When: 3차 수정 | ||
| findWithDays().updateChallengeDays(List.of(ChallengeDays.SATURDAY, ChallengeDays.SUNDAY)); | ||
| flushAndClear(); | ||
|
|
||
| // Then | ||
| assertThat(findDays()).containsExactlyInAnyOrder(ChallengeDays.SATURDAY, ChallengeDays.SUNDAY); | ||
| assertThat(countAllRows()).isEqualTo(2); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("중복된 요일이 요청으로 들어와도 중복 제거되어 저장되어야 한다") | ||
| void updateChallengeDays_withDuplicatedRequest_appliesDistinct() { | ||
| // When: 요청 자체에 중복 요일이 포함된 경우 | ||
| Challenge challenge = findWithDays(); | ||
| challenge.updateChallengeDays(List.of( | ||
| ChallengeDays.MONDAY, ChallengeDays.MONDAY, ChallengeDays.MONDAY, ChallengeDays.TUESDAY)); | ||
| flushAndClear(); | ||
|
|
||
| // Then | ||
| assertThat(findDays()).containsExactlyInAnyOrder(ChallengeDays.MONDAY, ChallengeDays.TUESDAY); | ||
| assertThat(countAllRows()).isEqualTo(2); | ||
| } | ||
|
|
||
| // ===================== helper ===================== | ||
|
|
||
| private Challenge findWithDays() { | ||
| return challengeRepository.findByIdWithDays(challengeId).orElseThrow(); | ||
| } | ||
|
|
||
| private List<ChallengeDays> findDays() { | ||
| return challengeDayJoinRepository.findByChallengeIdIn(List.of(challengeId)).stream() | ||
| .map(ChallengeDayJoin::getDay) | ||
| .toList(); | ||
| } | ||
|
|
||
| // 다른 챌린지가 없는 테스트이므로 전체 행 수 = 해당 챌린지의 요일 행 수 | ||
| private long countAllRows() { | ||
| return challengeDayJoinRepository.count(); | ||
| } | ||
|
|
||
| private void flushAndClear() { | ||
| entityManager.flush(); | ||
| entityManager.clear(); | ||
| } | ||
|
|
||
| private void addDays(Challenge challenge, ChallengeDays... days) { | ||
| Arrays.stream(days).forEach(day -> challenge.getChallengeDays().add( | ||
| ChallengeDayJoin.builder() | ||
| .challenge(challenge) | ||
| .dayOfWeek(day) | ||
| .build() | ||
| )); | ||
| } | ||
|
|
||
| private Challenge createChallenge() { | ||
| return Challenge.builder() | ||
| .title("요일 교체 테스트") | ||
| .description("테스트 설명") | ||
| .startDate(LocalDateTime.now().plusDays(3)) | ||
| .status(ChallengeStatus.UPCOMING) | ||
| .category(Category.values()[0]) | ||
| .verificationType(VerificationType.values()[0]) | ||
| .isPublic(true) | ||
| .isViewerMode(false) | ||
| .maxParticipants(10) | ||
| .currentParticipants(1) | ||
| .verifyStartTime(LocalTime.of(9, 0)) | ||
| .verifyEndTime(LocalTime.of(18, 0)) | ||
| .likeCount(0) | ||
| .build(); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.