main.com.sceyt.chatuikit.persistence.dao.LoadRangeDao.kt Maven / Gradle / Ivy
package com.sceyt.chatuikit.persistence.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.sceyt.chatuikit.persistence.entity.messages.LoadRangeEntity
@Dao
interface LoadRangeDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(entity: LoadRangeEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(entities: List)
@Query("select * from LoadRange where channelId =:channelId and ((startId >=:end and endId <=:start)" +
" or (endId >=:start and startId <= :end) or startId =:messageId or endId =:messageId)")
suspend fun getLoadRanges(start: Long, end: Long, messageId: Long, channelId: Long): List
@Query("select * from LoadRange where channelId =:channelId order by startId")
suspend fun getAll(channelId: Long): List
@Query("delete from LoadRange where channelId =:channelId")
suspend fun deleteChannelLoadRanges(channelId: Long)
@Query("delete from LoadRange where rowId in (:rowIds)")
suspend fun deleteLoadRanges(vararg rowIds: Long)
@Transaction
suspend fun updateLoadRanges(start: Long, end: Long, messageId: Long, channelId: Long) {
val ranges = getLoadRanges(start, end, messageId, channelId)
val minDb = ranges.minByOrNull { it.startId }?.startId ?: start
val maxDb = ranges.maxByOrNull { it.endId }?.endId ?: end
val min = minOf(minDb, start)
val max = maxOf(maxDb, end)
if (ranges.size == 1 && min >= ranges[0].startId && max <= ranges[0].endId)
return
if (ranges.isNotEmpty())
deleteLoadRanges(*ranges.map { it.rowId }.toLongArray())
insert(LoadRangeEntity(min, max, channelId))
}
}