Skip to content

Commit

Permalink
Merge pull request #204 from SOPT-all/mod/#203-fix-duplicate-search
Browse files Browse the repository at this point in the history
[MOD/#203] 최근 검색어 중복을 제거 하도록 수정합니다
  • Loading branch information
angryPodo authored Feb 21, 2025
2 parents 924231c + 545a191 commit 3b58502
Showing 1 changed file with 35 additions and 18 deletions.
53 changes: 35 additions & 18 deletions app/src/main/java/com/spoony/spoony/core/database/SearchDao.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,46 @@ interface SearchDao {
@Query("DELETE FROM search")
suspend fun deleteAllSearches()

// 최신순으로 최대 6개의 검색어 가져오기
@Query("SELECT * FROM search ORDER BY id DESC LIMIT 6")
// 특정 검색어 존재 여부 확인
@Query("SELECT EXISTS(SELECT 1 FROM search WHERE text = :searchText)")
suspend fun isSearchExists(searchText: String): Boolean

// 가장 오래된 검색어 삭제
@Query("DELETE FROM search WHERE id IN (SELECT id FROM search ORDER BY id ASC LIMIT 1)")
suspend fun deleteOldestSearch()

// 최신순으로 최대 검색어 가져오기
@Query("SELECT * FROM search ORDER BY id DESC LIMIT " + MAX_RECENT_SEARCHES)
suspend fun getRecentSearches(): List<SearchEntity>

// 검색어 추가 시, 최근 6개만 유지하도록 처리
// 전체 검색어 개수 가져오기
@Query("SELECT COUNT(*) FROM search")
suspend fun getSearchCount(): Int

// 검색어 추가 시, 중복 체크 및 최근 검색어 유지하도록 처리
@Transaction
suspend fun addSearchWithLimit(searchText: String) {
// 새 검색어 삽입
insertSearch(SearchEntity(text = searchText))

// 6개 초과 검색어 삭제
val allSearches = getAllSearches()
if (allSearches.size > 6) {
val excessSearches = allSearches.drop(6)
excessSearches.forEach { deleteSearchById(it.id) }
// 검색어 정규화 - 앞뒤 공백 제거
val trimmedText = searchText.trim()

// 빈 문자열이나 공백만 있는 경우 저장하지 않음
if (trimmedText.isBlank()) return

// 이미 존재하는 검색어인 경우 기존 항목 삭제
if (isSearchExists(trimmedText)) {
deleteSearchByText(trimmedText)
}
}

// 특정 ID 검색어 삭제
@Query("DELETE FROM search WHERE id = :id")
suspend fun deleteSearchById(id: Int)
// 검색어가 최대 개수 이상인 경우 가장 오래된 검색어 삭제
if (getSearchCount() >= MAX_RECENT_SEARCHES) {
deleteOldestSearch()
}

// 전체 검색어 가져오기
@Query("SELECT * FROM search ORDER BY id DESC")
suspend fun getAllSearches(): List<SearchEntity>
// 새로운 검색어 추가
insertSearch(SearchEntity(text = trimmedText))
}

companion object {
private const val MAX_RECENT_SEARCHES = 6
}
}

0 comments on commit 3b58502

Please sign in to comment.